Curiously Recurring Template Pattern - Polymorphic Copy Construction

Polymorphic Copy Construction

When using polymorphism, one quite often needs to create copies of objects by the base class pointer. A commonly used idiom for this is adding a virtual clone function that is defined in every derived class. The CRTP pattern can be used to avoid having to duplicate that function or other similar functions in every derived class.

// Base class has a pure virtual function for cloning class Shape { public: virtual ~Shape {} virtual Shape *clone const = 0; }; // This CRTP class implements clone for Derived template class Shape_CRTP : public Shape { public: virtual Shape *clone const { return new Derived(static_cast(*this)); } }; // Every derived class inherits from Shape_CRTP instead of Shape class Square: public Shape_CRTP {}; class Circle: public Shape_CRTP {};

This allows obtaining copies of squares, circles or any other shapes by shapePtr->clone.

Read more about this topic:  Curiously Recurring Template Pattern

Famous quotes containing the words copy and/or construction:

    I come to this land to ride my horse,
    to try my own guitar, to copy out
    their two separate names like sunflowers, to conjure
    up my daily bread, to endure,
    somehow to endure.
    Anne Sexton (1928–1974)

    When the leaders choose to make themselves bidders at an auction of popularity, their talents, in the construction of the state, will be of no service. They will become flatterers instead of legislators; the instruments, not the guides, of the people.
    Edmund Burke (1729–1797)