CPP Programming
About Lesson

When a derived class is getting more than one copy of properties due to indirect base class, it is known as Diamond problem.

Diamond problem can also be solved in two ways:

  1. Function Overriding
  2. Virtual base class

Virtual Base Class: When an indirect base class is giving more than one copy of properties to a derived class in Hybrid inheritance it causes ambiguity.  To avoid this, we make the indirect class as virtual base class to its direct derived classes.

Making an indirect base class virtual ensures that only one copy of properties of indirect classes are available to derived classes (i.e. Grand Children) of its direct derived classes later.

The keywords virtual and public/private/protected can be used in any order.

#include<iostream>
using namespace std;

class grandparent
{
int a;
public:
void seta()
{
a=1;
}
void showa()
{
cout<<"a= "<<a<<endl;
}
};

class parent1:virtual public grandparent
{
int x;
public:
void setx()
{
x=10;
}
void showx()
{
cout<<"x= "<<x<<endl;
}
void printmsg()
{
cout<<"msg from parent1"<<endl;
}
};

class parent2: virtual public grandparent
{
int y;
public:
void sety()
{
y=10;
}
void showy()
{
cout<<"y= "<<y<<endl;
}
void printmsg()
{
cout<<"msg from parent2"<<endl;
}
};

class child:public parent1,public parent2
{
int z;
public:
void setz()
{
z=10;
}
void showz()
{
cout<<"z= "<<z<<endl;
}

};

int main()
{
child obj;
obj.seta();
obj.showa();

}

You cannot copy content of this page