Cyker
Cyker

Reputation: 10914

Ambigious functions from different base classes in C++

The following code:

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

class Base2
{
public:
    void go(int a) {}
};

class Derived : public Base1, public Base2 {};

int main()
{
    Derived d;

    d.go(3);

    return 0;
}

will give an error during compilation:

g++ -o a a.cc
a.cc: In function ‘int main()’:
a.cc:19:7: error: request for member ‘go’ is ambiguous
a.cc:10:10: error: candidates are: void Base2::go(int)
a.cc:4:10: error:                 void Base1::go()
make: *** [a] Error 1

It's easy to see the prototypes in base classes are different. But why cannot the compiler detect this and automatically choose the matching one?

Upvotes: 0

Views: 104

Answers (1)

Superman
Superman

Reputation: 3081

Function overloading is not allowed across class boundaries. You can fix this by writing the Derived class like so -

class Derived : public Base1, public Base2
{
public:
    using Base1::go;
    using Base2::go;
};

Upvotes: 4

Related Questions