Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ multiple inheritance ambiguous

Tags:

c++

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?

like image 543
Raj Shekar Avatar asked Sep 27 '22 04:09

Raj Shekar


2 Answers

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

like image 179
JorenHeit Avatar answered Nov 15 '22 10:11

JorenHeit


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)();
like image 26
DhruvJoshi Avatar answered Nov 15 '22 09:11

DhruvJoshi