More C++ Idioms/Calling Virtuals During Initialization

= Calling Virtuals During Initialization =

Intent
Simulate the calling of virtual functions during object initialization.

Also Known As
Dynamic Binding During Initialization idiom

Motivation
Sometimes it is desirable to invoke virtual functions of derived classes while a derived object is being initialized. Language rules explicitly prohibit this from happening because calling member functions of a derived object before the derived part of the object is initialized is dangerous. It is not a problem if the virtual function does not access data members of the object being constructed, but there is no general way of ensuring it.

Solution and Sample Code
There are multiple ways of achieving the desired effect. Each has its own pros and cons. In general the approaches can be divided into two categories. One using two phase initialization and the other one uses only single phase initialization.

The two phase initialization technique separates object construction from initializing its state. Such a separation may not always be possible. Initialization of an object's state is clubbed together in a separate function, which could be a method or a free standing function.

Using a non-member function.
The factory function can be moved inside the base class but it has to be static.

Constructors of class Derived should be made private to prevent users from accidentally using them. Interfaces should be easy to use correctly and hard to use incorrectly. The factory function should then be a friend of the derived class. In case of member create function, the Base class can be a friend of Derived.

Without using two phase initialization.
Achieving the desired effect using a helper hierarchy is described below, but an extra class hierarchy has to be maintained, which is undesirable. Passing pointers to static member functions is C'ish. The Curiously Recurring Template Pattern idiom can be useful in this situation.

Using Base-from-member idiom, more complex variations of this idiom can be created.

Related Idioms
More C++ Idioms/初期化中の仮想関数呼び出し(Calling Virtuals During Initialization)