CS Electrical And Electronics
@cselectricalandelectronics

How to solve ambiguity problem in inheritance?

All QuestionsCategory: Cpp LanguageHow to solve ambiguity problem in inheritance?
CS Electrical And Electronics Staff asked 4 years ago

I need short information with code.

1 Answers
CS Electrical And Electronics Staff answered 4 years ago

The ambiguity can be solved by defining a named instance within the derived class using the class resolution operator.

Code 01:

#include <iostream>
using namespace std;
class M
{
public:
void display() { cout << “\n class M”; }
};
class N
{
public:
void display() { cout <<“\n class N”; }
};
class P : public M, public N
{
public:
void display(void)
{
M :: display();
}
};
int main()
{
P p;
p.display();
}

This code displays “class M” as output.

Code 02:

This code will display both the value of the class.

#include <iostream>
using namespace std;
class A{
public: void display()
{
cout<<” A\n “;
}
};
class B : public A
{
public:
void display(void)
{
cout<<” B\n “;
}
};
int main()
{
B b;
b.display();         //invokes display in B
b.A::display();      //invokes display in A
b.B::display();        //invokes display in B
}