Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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,
  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.

Pankaj Mishra
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap