AMBIGUITY IN INHERITANCE
In Multiple Inheritance:-
ambiguity when a function with same name
appears in more than one base class.
Class M
{
Public:
void display(void)
{
Cout<<“class M”;
}
};
Class N
{
public:
Void display(void)
{
Cout<<“Class N”;
}
};
Which display function is
used by derived class ???
Class P:public M,public N
{
Public:
Void display(void) //overrides display() of M &N
{
M::display(); //named instance is defined
}
};
Int main()
{
Pp;
p.display();
}
In single inheritance:-
Class A
{
public:
Void display()
{
cout<<“A”;
}
};
Class B:public A
{
Public:
Void display()
{
Cout<<“B”;
}
};
In this case, the function in derived class
overrides the inherited function
simple call to display() by B type object
creates ambiguity.
The func. defined in A invoked using (::)
void main()
{
Bb; // derived class obj
b.display(); //ambiguity
b.A::display(); //invokes display() in A
b.B::display(); //invokes display() in B
}
Multipath Inheritance
The child has 2 direct base classes ‘parent 1’,
’parent 2’.
the 2 parents have a common base class
‘grandparent’
Child inherits the traits from grandparent via.
2 diff paths.
all the public and protected members of
grandparent are inherited twice into child via.
Parent 1 & parent 2.
Hence, duplicate sets of members inherited
causing AMBIGUITY.
VIRTUAL BASE CLASS
Class A //grandparent
{
…..
};
Class B1:virtual public A //parent 1
{
};
Class B2:public virtual A //parent 2
{
}
Class C:public B1,public B2 // child
{
}; //only 1 copy will be inherited
NITIN SHARMA
09-ITMG-1054-CSE