Multipath Inheritance in C++ implements the use of Virtual Classes.
We make the base class 'virtual' by adding the keyword 'virtual' during declaration of Derived class.
#include <iostream>
using namespace std;
class A
{
public:
int a1;
A()
{
cout<<"Constructor of Base Class A";
}
};
class B:public virtual A //virtual public A is also OK
{
public:
int a2;
B()
{
cout<<"\nConstructor of Base Class B";
}
};
class C:public virtual A
{
public:
int a3;
C()
{
cout<<"\nConstructor of Class C";
}
};
class D:public B,public C
{
public:
int a4;
D()
{
cout<<"\nConstructor of Derived Class D\n\n";
}
};
int main()
{
D obj;
obj.a1=10;
obj.a2=20;
obj.a3=30;
obj.a4=40;
cout<<"a="<<obj.a1;
cout<<"\nb="<<obj.a2;
cout<<"\nc="<<obj.a3;
cout<<"\nd="<<obj.a4;
return 0;
}
We make the base class 'virtual' by adding the keyword 'virtual' during declaration of Derived class.
#include <iostream>
using namespace std;
class A
{
public:
int a1;
A()
{
cout<<"Constructor of Base Class A";
}
};
class B:public virtual A //virtual public A is also OK
{
public:
int a2;
B()
{
cout<<"\nConstructor of Base Class B";
}
};
class C:public virtual A
{
public:
int a3;
C()
{
cout<<"\nConstructor of Class C";
}
};
class D:public B,public C
{
public:
int a4;
D()
{
cout<<"\nConstructor of Derived Class D\n\n";
}
};
int main()
{
D obj;
obj.a1=10;
obj.a2=20;
obj.a3=30;
obj.a4=40;
cout<<"a="<<obj.a1;
cout<<"\nb="<<obj.a2;
cout<<"\nc="<<obj.a3;
cout<<"\nd="<<obj.a4;
return 0;
}