C++ Why the call is ambigous?

class myClass {
   int arr[100];
public:
    void *get(long i, void* const to) const;
    void *get(long i, bool nog);
    void *tstfn(void* const to) { return get(0L,to); }
};

gcc -Wall says:

dt.cpp: In member function ‘void* myClass::tstfn(void*)’:
dt.cpp:6:49: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: [enabled by default]
dt.cpp:4:9: note: candidate 1: void* myClass::get(long int, void*) const
dt.cpp:5:9: note: candidate 2: void* myClass::get(long int, bool)

Upvotes: 15

Views: 1426

Answers (3)

Ajay
Ajay

Reputation: 18431

Simply because your testfn is a non-const function, which would call the non-const version of get. The non-const function get, takes bool not const void*. Had only one get function was there (possibly taking void* as the second argument, irrespective of its constness), then would be called without ambiguity.

Upvotes: 6

Anton Savin
Anton Savin

Reputation: 41301

Because void *get(long i, void* const to) is const.

This means that calling it from tstfn (which is non-const) would require qualification conversion for this from myClass* to const myClass*, so calling both functions would require a conversion for the arguments (this is treated in the same way as other arguments), so the call is ambiguous.

Upvotes: 13

Mike Seymour
Mike Seymour

Reputation: 254501

Both function calls require a type conversion:

  • calling the void* function requires adding a const qualifer to this
  • calling the bool function requires converting to from void* to bool.

So, by the overload resolution rules, neither is a "better" match than the other, and the call is considered ambiguous.

Perhaps you can add const to the second function; perhaps you could remove it from the first (although I'd prefer not to); perhaps you can do an explicit type conversion of either this or to to force your preferred override.

Upvotes: 26

Related Questions