20

I was trying to create two classes, the first with a non-const implementation of the functions, the second with a const implementation. Here is a small example:

class Base {
protected:
  int some;
};

class A : public virtual Base {
  const int& get() const {
    return some;
  }
};

class B : public virtual Base {
  int& get() {
    return some;
  }
};

class C : public A, B {};

C test;
test.get(); // ambiguous 

The call to the get function is ambiguous. No matter that the const version needs to match more requirements. (Calling get on const C is ambiguous as well, but there is one possible function to call.) Is there a reason for such behaviour in the standard? Thanks!

1

2 Answers 2

19

Ambiguity occurs when compiler tries to figure out to what entity does the name get refer to, prior to overload resolution. It can be a name of function from class A or from class B. In order to build a list of overloads complier needs to select just one of the classes to pull functions from. In order to fix it you can bring that name from both of the base classes into derived class (and make them public):

class C : public A, public B { public: using A::get; public: using B::get; };
Sign up to request clarification or add additional context in comments.

2 Comments

An annoying C++ niggle!
An important C++ protection: if adding a function to a base class changed the overload set your code could quietly break; with this rule it breaks noisily.
14

The problem is that you don't actually have one unified overload-set, in which the mutable variant would be unambiguously best, but two distinct overload-sets, in A and B, and the compiler will not automatically merge them.

Put

using A::get;
using B::get;

in C to merge the overload-sets and thus resolve the ambiguity.

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.