wha is the diamond problem? how to resolve it?

The diamond problem arises from the multiple inheritance.
This can be explained by 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();
....
}

The receiver class uses the write method from base class, while the transmitter class overrides the write method. When invoking write() from radio, the compiler doesn't know which write method needs to be called.

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't 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();
...
}



Please look at the link for details:
http://www.cprogramming.com/tutorial/virtual_inheritance.html

No comments:

Post a Comment