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?

+4


source to share


4 answers


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()

).

+3


source


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)();

      

+1


source


Multiple inheritance ambiguity resolution: An ambiguity can be resolved by using the scoping operator to specify the class in which the member function lies below:

obj.a :: abc();

      

This operator calls the name of the abc () function, which are in the base class a.

-1


source


This can be solved using the operator ::

ob->N::display(); //this calls display() from class N

      

-1


source







All Articles