0

I'm trying to build a heterogeneous list that allocates memory to the heterogeneous array dynamically. I'm having some trouble with the declarations necessary to make this work. So far I have something like:

class Class1
{
 public:
 Class1 * GetList( int i, Class1& c );
 void Create( int size );

 private:
 Class1 ** list1;
};

class Class2: public Class1
{
  ...
};

Class1 * GetList( int i, Class1& c )
{
  return c.list1[i];
}

void Class1::Create( int size )
{
 list1 = new Class1*[size];
}

int main()
{ 
 Class1 c;
 int size = 0;

 cin >> size;

 c.Create( size );

 for( int i = 0; i < size; i ++ )
 {
    c.GetList( i, c ) = new Class2;

    c.GetList( i, c )->SetParams( some params );  
 }

}

I'm wondering if I'm using the heterogeneous list to store pointers of the parent class dynamically and call them in main correctly. Any help would be much appreciated.

Victor Brunell
  • 5,668
  • 10
  • 30
  • 46
  • `Class1 * GetList( int i, Class1& c );` either this function should be static, either `c` is useless and you should use `this`. – Johan Nov 19 '13 at 22:19
  • Why aren't you just using a `std::vector` ? Is this a assignment ? – Johan Nov 19 '13 at 22:26
  • We aren't allowed to use the vector class in this assignment. I see my mistake in the declaration of GetList. Would something like this work: Class1 * GetList( int i ) with return list[i]; ? – Victor Brunell Nov 19 '13 at 23:16

1 Answers1

0

According to your usage and following what we've said in the comments, you should change GetList for this:

Class1 *& GetList( int i )
{
 return list1[i];
}

Mind the &. Otherwise your assignment using GetList(i) =... will be useless.

Johan
  • 3,728
  • 16
  • 25