Playing with multiple inheritance in cpp

We all know about that diamond problem..

A

B       C

D

This is a perfect situation for multiple inheritance. Here A can be reached in two way from D. So if we write a code without virtual keyword, a’s constructor will be called twice, which will create ambiguity about which object we are referring to.

Without using virtual keyword constructor call will be like this :-

A’s constructor called
b’s constructor called
A’s constructor called
c’s constructor called
d’s constructor called

After using virtual keyword :

A’s constructor called
b’s constructor called
c’s constructor called
d’s constructor called

As you can see A is accessed only once . Now suppose there are a few more classes above d. Some parents of d are using virtual keyword to access grandparent A, and some parents of d are not using virtual keyword. So what will happen in that scenario ?

Answer is very simple. A’s object will be created only once for classes using virtual keyword, for everyone else who are not using virtual , separate objects of A will be created.

Here I have added one class m which is parent of d and accessing A without virtual keyword. Output is like…

A’s constructor called
b’s constructor called
c’s constructor called
A’s constructor called
m’s constructor called
d’s constructor called

For B and C one A object and for m a separate A object is created.

Here is the code to experiment with

#include "iostream"
using namespace std;
class a
{
public:
a()
{
cout< }

};
class b: virtual public a
{
public:
b()
{
cout< }

};
class c: virtual public a
{
public:
c()
{
cout< }

};
class m: public a
{
public:
m()
{
cout< }

};
class d: public b, public c , public m
{
public:
d()
{
cout< }

};

int main()
{
d obj;
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *