How to copy/create derived class instance from a pointer to a polymorphic base class?

You add a virtual Base* clone() const = 0; in your base class and implement it appropriately in your Derived classes. If your Base is not abstract, you can of course call its copy-constructor, but that’s a bit dangerous: If you forget to implement it in a derived class, you’ll get (probably unwanted) slicing.

If you don’t want to duplicate that code, you can use the CRTP idiom to implement the function via a template:

template <class Derived>
class DerivationHelper : public Base
{
public:
  virtual Base* clone() const
  {
    return new Derived(static_cast<const Derived&>(*this)); // call the copy ctor.
  }
};

class Derived1 : public DerivationHelper <Derived1> { ... };
class Derived2 : public DerivationHelper <Derived2> { ... };

Leave a Comment