Question

Consider following example (link to ideone):

#include <iostream>

class Base1
{
public:
    void doit(){}
};

class Base2
{
    void doit(int x){}
};

class Derrived : public Base1, public Base2
{
};

using namespace std;

int main()
{
   cout << "Hello World" << endl;
   Derrived d;
   d.doit(); // doesn't work - error: request for member ‘doit’ is ambiguous
   d.::Base1::doit(); //works
   return 0;
}

Both Base1 and Base2 have member function doit with different input arguments, so overloads in theory should be resolved automatically. However, attempt to call d.doit(); fails with error

prog.cpp: In function ‘int main()’:
prog.cpp:36:6: error: request for member ‘doit’ is ambiguous
    d.doit(); // doesn't work - error: request for member ‘doit’ is ambiguous
      ^
prog.cpp:18:7: note: candidates are: void Base2::doit(int)
  void doit(int x)
       ^
prog.cpp:6:10: note:                 void Base1::doit()
     void doit()
          ^

and I have to type d.::Base1::doit(); to make it work.

Why compiler is unable to resolve which function to call without me explicitly specifying it? Is it expected behavior??

Was it helpful?

Solution

Yes, this is expected behaviour.

Before overload resolution, name lookup is performed, which has its own set of rules. It has to find an unambiguous name and there isn't one in your case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top