We have the Base and Derived class, which comes from Base .
In some other class, we want to have a member of type shared_ptr<Base> .
We cannot use the Base type directly, because direct copying will exclude subclasses.
However, we still want to “copy” the Base object (or subclass) on top of the construct, because we want to exclude the possibility of its modification.
The classic way to handle this is to put the virtual member function clone() in the Base class, which every subclass of Base can implement. Each clone() then simply returns a "copy" of itself - for example, Derived will return make_shared<Derived>(*this) .
The problem with this approach is that each new subclass of Base is required to implement this clone() function. The code in each clone() is rather a template, and it seems somewhat unnatural to repeat it all the time.
Any better ways to do this with C ++ 11?
source share