Home > Article > Backend Development > How to Create Derived Class Instances from a Polymorphic Base Class Pointer: A Guide to Clone Methods and the CRTP Idiom
Creating Derived Class Instances from a Pointer to a Polymorphic Base Class
This issue arises when attempting to create a copy of a derived class instance from a pointer to its polymorphic base class. A naive approach involves numerous type checks and dynamic casts, checking for each potential derived type and employing the new operator. However, a more refined solution is available.
The key is to incorporate a virtual method, Base* clone() const = 0;, into the base class. Each derived class must then override this method to create a specific clone. For instance:
<code class="cpp">class Base { virtual ~Base(); virtual Base* clone() const = 0; }; class Derived1 : public Base { virtual Base* clone() const override { return new Derived1(*this); } }; class Derived2 : public Base { virtual Base* clone() const override { return new Derived2(*this); } };</code>
By calling clone() on the base pointer, you can obtain a new instance of the specific derived class. This streamlined approach eliminates the need for type checks or dynamic casts, enhancing code clarity and efficiency.
However, if you wish to avoid code duplication, consider leveraging the CRTP (Curiously Recurring Template Pattern) idiom. A template class can be defined as follows:
<code class="cpp">template <class Derived> class DerivationHelper : public Base { public: virtual Base* clone() const override { return new Derived(static_cast<const Derived&>(*this)); } }; class Derived1 : public DerivationHelper<Derived1> { ... }; class Derived2 : public DerivationHelper<Derived2> { ... };</code>
This template class, when inherited by the derived classes, provides the necessary implementation for the clone() method, eliminating the need for separate overrides in each derived class.
The above is the detailed content of How to Create Derived Class Instances from a Polymorphic Base Class Pointer: A Guide to Clone Methods and the CRTP Idiom. For more information, please follow other related articles on the PHP Chinese website!