The typical pattern when you want to copy a polymorphic class is adding a virtual clone method and implement it in each derived class like this:
Base* Derive
You can use this generic CRTP code
template
struct Clonable : Base {
virtual Base* do_clone() {
return new Derived(*static_cast(this));
}
Derived* clone() { // not virtual
return static_cast(do_clone());
}
using Base::Base;
};
struct empty {};
struct A : Clonable {};
struct B : Clonable {};
It can be generalised to smart pointers and multiple bases if desired.