Explain Virtual Base Class Syntax with example Program

Virtual Base Class:
The mechanism of deriving a class from other derived classes, which are, derived from the same base class, is called multipath inheritance. An object of multipath inheritance having two sets of grand parent class members. They are one from parent -1 and the other form parent-2. The compiler generates ambiguity in function call if you try to call grand parent members using child object. The duplication of inherited members due to multiple paths can be avoided by making the common base class as virtual base class.
class grand parent
{
-----------
-----------
};
class parent-1:public virtual grand parent
{
-----------
-----------
};
class parent-2 : virtual public grand parent
{
-----------
-----------
};
class child : public parent -1, public parent -2
{ // it will contain only one
-----------
----------- // copy of members of
----------- // grand parent
};
Example:
#include<iostream.h>
#include<conio.h>
class base
{ protected:
int a,b;
public:
void get()
{ cout<<"enter a=";
cin>>a;
cout<<"enter b=";
cin>>b;}
void show()
{ cout<<"a="<<a<<"\nb="<<b;}
};
class d1 :virtual public base
{ protected :int c;
public:
void get1(){cout<<"enter c=";
cin>>c;}
void show1()
{ cout<<"\nc="<<c;
}
};
class d2 :virtual public base
{ protected:int d;
public:
void get2(){cout<<"enter d=";
cin>>d;}
void show2()
{ cout<<"\nd="<<d;
}
};
class child : public d1,public d2
{ int e;
public:
void get3(){cout<<"enter e=";
cin>>e;}
void show3()
{ cout<<"\ne="<<e;
}
};
void main()
{ clrscr();
child c1;
c1.get();
c1.show();
c1.get1();
c1.show1();
c1.get2();
c1.show2();
c1.get3();
c1.show3();
getch();
}
Labels: C++