Inheritance B
Inheritance B
In this type of inheritance, more than one sub class is inherited from a single base
class. i.e. more than one derived class is created from a single base class.
A derived class with two base classes and these two base classes have one common
base class is called multipath inheritance. An ambiguity can arise in this type of
inheritance.
In the above example, both ClassB & ClassC inherit ClassA, they both have single copy
of ClassA. However ClassD inherit both ClassB & ClassC, therefore ClassD have two
copies of ClassA, one from ClassB and another from ClassC.
If we need to access the data member a of ClassA through the object of ClassD, we
must specify the path from which a will be accessed, whether it is from ClassB or
ClassC, bco’z compiler can’t differentiate between two copies of ClassA in ClassD.
#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
class ClassB : virtual public ClassA
{
public:
int b;
};
class ClassC : virtual public ClassA
{
public:
int c;
};
class ClassD : public ClassB, public ClassC
{
public:
int d;
};
void main()
{
ClassD obj;
obj.a = 10; //Statement 3
obj.a = 100; //Statement 4
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< "\n A : "<< obj.a;
cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;
}
Output:
A : 100
B : 20
C : 30
D : 40
According to the above example, ClassD has only one copy of ClassA, therefore,
statement 4 will overwrite the value of a, given at statement 3.