Try it here
Subscribe
The diamond problem Solution C++

Solving the Diamond Problem with Virtual Inheritance

solving_the_diamond_problem_with_virtual_inheritance

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.

Writer profile pic

Uk01 on Sep 01, 2020 at 12:05 am


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.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.