More C++ Idioms/Base-from-Member

= Base-from-Member =

Intent
To initialize a base class from a data-member of the derived class.

Motivation
In C++, base classes are initialized before any member of the derived class. The reason for this is that members of a derived class may use the base part of the object. Therefore, all the base parts (i.e., all base classes) must be initialized before members of the derived class. Sometimes, however, it becomes necessary to initialize a base class from a data member that is available only in the derived class. It sounds contradictory to the rules of C++ language because the parameter (a member of derived class) that is passed to the base class constructor must be fully initialized. This creates a circular initialization problem (an infinite regress).

The following code, obtained from the Boost libraries, shows the problem.

The above code snippet shows a case where the programmer is interested in customizing the  class. They do so in  by inheriting from. The  class is used as a member in   class, which is a kind of. The  class, however, needs a pointer to a   class, or its derived class. The type of pointer to  is suitable but passing it makes sense only if   is initialized. However, it won’t be initialized unless all base classes are initialized. Hence the infinite regress. The base-from-member idiom addresses this problem.

Solution and Sample Code
This idiom makes use of the fact that base classes are initialized in the order they are declared. The derived class controls the order of its base classes, and in turn, controls the order in which they are initialized. In this idiom, a new class is added just to initialize the member in the derived class that is causing the problem. This new class is introduced in the base-class-list before all other base classes. Because the new class comes before the base class that needs the fully constructed parameter, it is initialized first and then the reference can be passed as usual. Here is the solution using base-from-member idiom.

The  class is the newly introduced class that now has the   member. The  class inherits from this new class and adds it before   in its base class list. This ensures that  is initialized before   and the pointer can be safely passed to it's constructor.

Known Uses

 * Boost Base from Member