I have a problem in C++ multiple inheritance. here is my code and when I call display() function it is giving me request for member `display' is ambiguous. But 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 any one tell why exactly this problem?
As was mentioned by many already, overload resolution does not include visibility (public, private and protected). Assuming you want only the public version visible in P, you should use a using declaration in the public interface of P:
class P: public M, public N
{
public:
    using N::display;
};
IMHO, this is far more elegant than having to provide the scope in every call (obj->N::display()).
Basically in C++, in case of multiple inheritance the derived class gets a copy of all methods of all parents. So when you do new P(), the new objects gets two different methods, with same name display(). And therefore there is an ambiguity.
Scope resolution will help you here.
//define function pointer
void (N::*pfn)() = &N::display;
//call function using pointer
(ob->*pfn)();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With