Stormenet
Stormenet

Reputation: 26468

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?

Upvotes: 4

Views: 4878

Answers (4)

Daniel Lidstr&#246;m
Daniel Lidstr&#246;m

Reputation: 10260

As others have said you need some type of cloning mechanism. You might want to check out the cloning_ptr by Kevlin Henney in his excellent paper Clone Alone.

Upvotes: 2

Moo-Juice
Moo-Juice

Reputation: 38825

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.

Upvotes: 4

Andreas Brinck
Andreas Brinck

Reputation: 52519

You could implement a pure virtual clone function in class A.

Upvotes: 2

frast
frast

Reputation: 2740

Add a virtual Clone() method to your classes.

A* copy = it->Clone();

class A {
    virtual A* Clone()
    {
        return new A(*this);
    }
};

Override Clone in derived classes. The implementation is the same as with class A.

Upvotes: 2

Related Questions