I fixed a bug recently.
In the following code, one of the overloaded function was const and the other one was not. The issue will be fixed by making both functions const.
My question is why compiler only complained about it when the parameter was 0.
#include <iostream>
#include <string>
class CppSyntaxA
{
public:
void f(int i = 0) const { i++; }
void f(const std::string&){}
};
int main()
{
CppSyntaxA a;
a.f(1); // OK
//a.f(0); //error C2666: 'CppSyntaxA::f': 2 overloads have similar conversions
return 0;
}
0is special in C++. A null pointer has the value of0so C++ will allow the conversion of0to a pointer type. That means when you callYou could be calling
void f(int i = 0) constwith anintwith the value of0, or you could callvoid f(const std::string&)with achar*initialized to null.Normally the
intversion would be better since it is an exact match but in this case theintversion isconst, so it requires "converting"ato aconst CppSyntaxA, where thestd::stringversion does not require such a conversion but does require a conversion tochar*and then tostd::string. This is considered enough of a change in both cases to be considered an equal conversion and thus ambiguous. Making both functionsconstor nonconstwill fix the issue and theintoverload will be chosen since it is better.