One of the problems that arises due to multiple inheritance is the diamond problem. A classical illustration of this is given by Bjarne Stroustrup (the creator of C++) in the following example:
class storable //this is the our base class inherited by transmitter and receiver classes { public: storable(const char*); virtual void read(); virtual void write(); virtual ~storable(); private: .... } class transmitter: public storable { public: void write(); ... } class receiver: public storable { public: void read(); ... } class radio: public transmitter, public receiver { public: void read(); .... }
Since both transmitter and receiver classes are using the method write() from the base class, when calling the method write() from a radio object the call is ambiguous; the compiler can't know which implementation of write() to use, the one from the transmitter class or the one from the receiver class.
To understand how this is works, let's take a look at how the objects are represented in memory. Inheritance simply puts the implementation of two objects one after another, but in this case radio is both a transmitter and a receiver, so the storable class gets duplicated inside the radio object. The g++ compiler will complain when compiling the code: error: 'request for member "write" is ambiguous', because it can figure out whether to call the method write() from storable::receiver::radio or from storable::transmitter::radio.
Fortunately, C++ allows us to solve this problem by using virtual inheritance. In order to prevent the compiler from giving an error we use the keyword virtual when we inherit from the base class storable in both derived classes:
class transmitter: public virtual storable { public: void read(); ... } class receiver: public virtual storable { public: void read(); ... }
When we use virtual inheritance, we are guaranteed to get only a single instance of the common base class. In other words, the radio class will have only a single instance of the storable class, shared by both the transmitter and receiver classes. By having a single instance of storable, we've resolved the compiler's immediate issue, the ambiguity, and the code will compile fine.
If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.