Copying a purley virtual class child

In short, this is what I have

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class A{
    A(){}
    virtual void pure() = 0;
}

class B : public A{
    B() : A() {}
    virtual void pure() {}
}

void method(A* a2) {}

// ...

A* a1 = new B();
method(a1);


I need a2 to be a deep copy of a1, but if I understand it correctly, then a2 should just be a pointer copy of a1. How do I make a2 be a different instance of B?

Thanks.
1
2
3
4
5
class A{
    A(){}
    virtual void pure() =0;
    virtual A* clone() =0;
};

This is probably the safest, most portable way to copy any A object.
Thanks. But do I return A* or B* in my derived class that implements it?
You can make the clone function return a B* in class B but when you call the clone function using a A* the return type will of course be A* because that's the return type of A::clone().
clone() creates a B object and returns a pointer to the A base object.

But back to your original question, method(A* a2) doesn't pass a copy of A or B. It passes a pointer to an A.
1
2
3
4
5
6
class B : public A {
    virtual A* clone() {return new B(*this);}
};

// ...
method(a1->clone());


Remember to delete the cloned object afterwards, or store it in a unique_ptr.
Last edited on
Topic archived. No new replies allowed.