While multiple inheritance is an extremely useful featureescpecially in large scale software, it can also lead to a problem known as the DDD, or "Dreadful Diamond on Derivation," or simply "The Diamond Problem," shown in the following code:
class ElectricAppliance{
int voltage,
public:
int getVoltage ( ) const { return voltage; }
} ;
class Radio : public ElectricAppliance { / * ...* / } ;
class Tape : public ElectricAppliance { / * ...* / } ;
class RadioTape: public Radio, public Tape { / * ..* / } ;
int main( )
{
RadioTape rt ;
int voltage = rt .getVoltage( ) ;
/* Error - ambiguous call. Two copies getVoltage( ) exist in rt*/
}
RadioTape is derived simultaneously from two base classes, each of which has its own copy of the methods and data members of
ElectricAppliance. Consequently, the object
rt has two
ElectricAppliance subobjects. In cases like this, where you need to reduplicate data methods from a common base class, you should use virtual inheritance:
class Radio : virtual public ElectricAppliance { / * ..* / } ;
class Tape : virtual public ElectricAppliance { / * ..* / } ;
class RadioTape: public Radio, public Tape { / * ..* / }
Now, class
RadioTape contains a single shared instance of
ElectricAppliance, so there are no ambiguities:
int voltage = rt .getVoltage( ) ; / /OK
Note: Because of the virtual keyword in the base-class portion of
Radio and
Tape, an instance of
ElectricAppliance will have have only a single, base subobject. This eliminates the ambiguities.