Search code examples
c++multiple-inheritancecopy-constructor

Vector of pointer to objects, need deep copy of vector, but the objects are the base of inherited objects


I want to have a deep copy of an vector with pointers to objects, but the object can either be C or B. I know confusing (the way I explain it), let me illustrate.

class A {
    A(const A& copyme) { }
    void UnableToInstantiateMeBecauseOf() =0;
};

class B {
    B(const B& copyme) : A(copyme) {}
};

class C {
    C(const C& copyme) : A(copyme) {}
};

std::vector<A*>* CreateDeepCopy(std::vector<A*>& list)
{
    std::vector<A*>* outList = new std::vector<A*>();

    for (std::vector<A*>::iterator it = list.begin(); it != list.end(); ++it)
    {
        A* current = *it;
        // I want an copy of A, but it really is either an B or an C
        A* copy = magic with current;
        outList->push_back(copy);
    }

    return outList;
}

How to create an copy of an object of which you don't what inherited type it is?


Solution

  • Use cloning:

    Copy object - keep polymorphism

    class Super
    {
    public:
        Super();// regular ctor
        Super(const Super& _rhs); // copy constructor
        virtual Super* clone() const = 0; // derived classes to implement.
    }; // eo class Super
    
    
    class Special : public Super
    {
    public:
        Special() : Super() {};
        Special(const Special& _rhs) : Super(_rhs){};
        virtual Special* clone() const {return(new Special(*this));};
    }; // eo class Special
    

    EDIT:

    I noticed in your question your base-class is abstract. That's fine, this model still works, I have amended.