5

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?

4
  • The ambiguity error is because despite the scope of the function in M, the call is ambiguous. Try using the scope resolution operator :: to help resolve where the call should be made: msdn.microsoft.com/en-us/library/b451xz31.aspx Commented Jul 29, 2015 at 9:16
  • 1
    visibility doesn't restrict the choice in overload. Commented Jul 29, 2015 at 9:25
  • You can resolve it by putting using N::display in the public interface of P. Commented Jul 29, 2015 at 9:25
  • thanks Martin and Joren. I got it.. Commented Jul 31, 2015 at 8:18

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Joren. This helps
1

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

Comments

-1

Solution of ambiguity in multiple inheritance: The ambiguity can be resolved by using the scope resolution operator to specify the class in which the member function lies as given below:

obj.a :: abc();

This statement invoke the function name abc() which are lies in base class a.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.