More C++ Idioms/Virtual Constructor

= Virtual Constructor =

Intent
To create a copy of an object or a new object without knowing its concrete type.

Also Known As
Factory Method of initialization

Motivation
Uses of calling member functions in a class hierarchy polymorphically are well known in the object-oriented programming community. It is a way of implementing the is-a (or more practically, behaves-as-a) relationship. Sometimes it is useful to call life-cycle management (creation, copy, and destruction) functions of a class hierarchy polymorphically.

C++ natively supports polymorphic destruction of objects using a virtual destructor. An equivalent support for creation and copying of objects is missing. In C++, creation of object(s) always requires its type to be known at compile-time. The Virtual Constructor idiom allows polymorphic creation of and copying of objects in C++.

Solution and Sample Code
The effect of a virtual constructor by a create member function for creation and a clone member function for copy construction as shown below.

The Manager class implements the two pure virtual functions and uses the type name (Manager) to create them. The function duplicate shows how virtual constructor idiom is used. It does not really know what it is duplicating. It only knows that it is cloning an Employee. The responsibility of creating the right instance is delegated to the derived classes. The duplicate function is therefore closed for modifications even though the class hierarchy rooted at Employee gets more sub-classes added in the future.

The return type of the clone and create member functions of the Manager class is not Employee but the class itself. C++ allows this flexibility in types where the return type of the over-ridden function can be a derived type of that of the function in the base class. This language feature is known as co-variant return types.

To handle resource ownership properly, the Resource Return idiom should be employed for the return types of clone and create functions as they are factory functions. If used, the return types (shared_ptr and shared_ptr) are no longer covariant return types and program should fail to compile. In such a case, the virtual constructor functions in the derived class should return the exact type as in the parent class.

Known Uses
std::function

Related Idioms

 * Resource Return
 * Polymorphic Exception