C ++ multiple inheritance is ambiguous
I have a problem with C ++ multiple inheritance. here is my code and when i call the display () function it gives me a request for the participant's `display 'is ambiguous. But the Class M display () function is private.
#include<iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;
class M
{
void display()
{
cout<<"Class M"<<endl;
}
};
class N
{
public:
void display()
{
cout<<"Class N"<<endl;
}
};
class P:public M,public N
{
};
int main()
{
P *ob = new P();
ob->display(); // Why its giving me ambiguity error? Since only one copy is there right!!
getch();
return 0;
}
Can anyone explain why exactly this problem is?
source to share
As many have mentioned, overload resolution does not include visibility ( public
, private
and protected
). Assuming you only want the P
public version to appear, you should use the using
public interface declaration P
:
class P: public M, public N
{
public:
using N::display;
};
IMHO, this is much more elegant than having to provide scope in every call ( obj->N::display()
).
source to share
Mostly in C ++, in the case of multiple inheritance, the derived class gets a copy of all methods of all parents. So when you execute new P()
, the new objects get two different methods with the same name display()
. And so there is ambiguity. Scope resolution will help you here.
//define function pointer
void (N::*pfn)() = &N::display;
//call function using pointer
(ob->*pfn)();
source to share