4

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Stormenet
  • 25,926
  • 9
  • 53
  • 65

4 Answers4

4

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.

Community
  • 1
  • 1
Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
2

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.

frast
  • 2,700
  • 1
  • 25
  • 34
2

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

Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
2

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.

Daniel Lidström
  • 9,930
  • 1
  • 27
  • 35