Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Jul 25, 2006



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Avoid the Diamond Problem when Using Inheritance in Loops

While multiple inheritance is an extremely useful feature—escpecially 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,
  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.

Pankaj Mishra
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date