I would like to know if there is a "default" approach to get a copy of a object of a derived class.
My class structure looks like this:
|------> A <------|
| ^ |
| | |
B1 B2 B3
Hereby, A is an abstract base class, which has a private B* member child_. Now, I would like to define the following method in A:
void set_child(const A& new_child) {
if (child_ != nullptr)
delete child_;
// Now I want a to create a copy of new_child
// (of the most specific derived class),
// without explicitly dispatching on its type.
child_ = ???
// I think, child_ = new A(child); does not work
}
What would be the most canonical way to do this? I thought about defining a virtual clone() method in each derived class, so that I could write
child_ = new_child.clone();
but then I have to touch every derived class.
I would be glad for your recommendations.
Thank you, Sven