indjev99 indjev99 - 3 months ago 11
C++ Question

Clone an object when I have a pointer to its base class?

I have multiple classes (let's say B and C), which inherit some abstract base class (let's say A). I have a pointer (p1) to class A, which is actually pointing to an object (o1) of class B or class C. Then I have another pointer (p2) to class A and I want to make it point to another object (o2) that is the same as o1. The problem is that at that moment I don't know what type o1 is of.

A* newObject() //returns pointer to A which actually points to an object of class B or class C
{
....
}
A * p1 = newObject();
A * p2 = //I want it to point to a new object that is the same as the object p1 is pointing to. How can I do that?


I need that because I am implementing a genetic algorithm and I have multiple types of controlling classes which I then want to mutate. And when something replicates I want the child to be the same as the parent and then I want to mutate the child. This means that p2 cannot be equal to p1 because then this will mutate the controller of the parent as well.

Answer

Add virtual method Clone() to the class.

class A {
public:
    virtual ~A() = default;

    auto Clone() const { return std::unique_ptr<A>{DoClone()}; }
    // ...
private:
    virtual A* DoClone() const { return new A(*this); }
};

class B : public A {
public:
    auto Clone() const { return std::unique_ptr<B>{DoClone()}; }
    // ...
private:
    // Use covariant return type :)
    B* DoClone() const override { return new B(*this); }
    // ...
};

class C : public A {
public:
    auto Clone() const { return std::unique_ptr<C>{DoClone()}; }
    // ...
private:
    // Use covariant return type :)
    C* DoClone() const override { return new C(*this); }
    // ...
};

and then

auto p2 = p1->Clone();
Comments