Search code examples
c++inheritancedynamic-memory-allocation

memory allocation and inherited classes in C++


Say I have these structs:

struct Base{
 ...
}

struct Derived:public Base{
 //everything Base contains and some more
}

I have a function in which I want to duplicate an array of these and then alter it.

void doStuff(Base *data, unsigned int numItems){
 Base *newdata = new Base[numItems];
 memcpy(newdata, data, numItems*sizeof(Base));
 ...
 delete [] newdata;
}

But if I used this function like so:

Base *data = new Derived[100];
doStuff(data, 100);

It wouldn't work, would it? Because Derived1 is larger than Base, so allocating for Base is not enough memory?


Solution

  • You could do this easily with a template:

    template< class T >void doStuff(T *data, unsigned int numItems)
    {
        T *newdata = new T[numItems];
        memcpy( newdata, data, sizeof( T ) * numItems );
        ...
        delete [] newdata;
    }
    

    Edit as per the comments: If you wanted to do this for a mixed collection things will get more complicated quickly ... one possible solution is this:

    struct Base{
        virtual Base* CopyTo()      { return new Base( *this ); }
    };
    
    struct Derived:public Base{
        virtual Derived* CopyTo()   { return new Derived( *this ); }
    
    };
    
    void doStuff( Base** ppArray, int numItems )
    {
        Base** ppNewArray   = new Base*[numItems];
        int count = 0;
        while( count < numItems )
        {
            ppNewArray[count] = ppArray[count]->CopyTo();
            count++;
        }
    
        // do stuff
    
        count = 0;
        while( count < numItems )
        {
            delete ppNewArray[count];
            count++;
        }
        delete[] ppNewArray;
    }