Search code examples
c++reallocderived

C++ Derived class array Reallocation


Sorry for confusing the topic, this was the original question:

How to reallocate an array of pointers to base class, that actually point to different derived classes?

I shouldnt use dynamic cast, typeid or RTTI here if possible..

EDIT I just realized i could try saving the array elements and just setting the pointers in new array to old elements.. But then how to do operator= or Cctor?

Or:

How to reallocate this array 'the bad way', by actually copying the elements?

An example:

class Base {...}
class Derived1 : public Base {...}
class Derived2 : public Base {...}

int main()
{
  int arrayLength=0, arrayMaxLength=3;

  Base **array=new Base*[arrayMaxlength];
  array[0]=new Derived1();
  array[1]=new Derived2();

  //Reallocation starts...
  Base **tmp=new Base*[arrayMaxLength*=2];

  for(int i=0;i<arrayLength;i++)
    tmp[i]=new Base(*array[i]);      //<------ What to put here instead of Base?


  //The unimportant rest of Reallocation..
  for(int i=0;i<arrayLength;i++)
    delete array[i];
  delete [] array;
  array=tmp;
}

Solution

  • You should not need to do any casting (dynamic or otherwise): just reuse the pointers

    Base **array=new Base*[arrayMaxlength]; 
    array[0]=new Derived1(); 
    array[1]=new Derived2(); 
    
    //Reallocation starts... 
    Base **tmp=new Base*[arrayMaxLength*=2]; 
    
    for(int i=0;i<arrayLength;i++) 
      tmp[i]=array[i]; 
    
    // ...
    

    The objects are already allocated and have the proper type. You can just copy the pointers themselves to the new array.

    Note that you will have to be careful not to delete the (objects pointed to by the) pointers in the old array, as that would invalidate the ones in the new (the object pointed to by the stored pointers does not exist any more) -- just delete the original array iself.

    If the management of pointers becomes burdensome, you can use some sort of shared pointer (the BOOST library offers a variety, for example)