C++ ambiguity resolution in inheritance
occasionally , we may face a problem in using the multiple inheritance, when a function with the same inheritance appears in more than one base class. consider the following two classes
class M
{
:
dipslay()
{
std::cout << "class M\n";
}
};
class N
{
:
display()
{
std::cout << "class N\n";
}
};
|
so which display() function is used by the derived class when we inherit these two classes?
we can solve this problem by defining a named instance within the derived class , using the class resolution operator with the function as shown
class P: M,
N
{
:
display()
{
M::display();
}
};
we can now use the derived class as follows
main()
{
P p;
p.display();
}
|
ambiguity may also arise in single inheritance application, for instance, consider the follow situation:
class A
{
:
display()
{
std::cout<<"A\n";
};
class B: A
{
:
display()
{
std::cout<<"B\n";
}
};
|
in this case the function in the derived class overrides the inheritance the inherited function and therefore, a simple call to display() by B type will invoke function defined in B only. however we may invoke the function defined in A by using the scope resolution
operator to specify the class
Example
main()
{
B b;
b.display();
b.A::display();
b.B::display();
}
|
This will produce the following output:
B
A
B
|