More C++ Idioms/Inner Class

= Inner Class =

Intent

 * Implementing multiple interfaces without multiple inheritance and yet provide natural looking up-casting.
 * Provide multiple implementations of the same interface in a single abstraction.

Motivation
Signature of a virtual function in two independent interfaces provided by two independent class libraries may collide. It is a problem especially when a single class has to implement both the colliding functions in different ways depending upon the interface you consider. For example,

The inner class idiom can help solve this problem.

Solution and Sample Code
Leaving the interface classes, Base1 and Base2 unchanged we can implement the Derived class as follows. Note the use of conversion operators in class Derived. (Derived class is really not a derived class!) The conversion operators allow conversion of Derived to Base1 even though they don't share inheritance relationship themselves! Use of member objects base1_obj and base2_obj eliminates the concern of object lifetime. Lifetime of member objects is same as that of the Derived object.

Related Idioms

 * Interface Class
 * Capability Query