why do we not see a "undefined call to overloaded function" error with the code bellow? just because int is a built in type? where in the standard can I find the guarantee for the conversion to built in type, such as in the code bellow?... thanks!
#include <iostream>
using namespace std;
class B {
public:
operator int(){ return 0; }
};
class A {
public:
A( int i ) { };
};
void f ( int i ) { cout << "overload f(int) was used!";};
void f ( A a ) { cout << "overload f(A) was used!" ;};
int main () {
B b;
f( b );
}
It has nothing to do with being a built-in type. You defined
operator int
forB
. This means that you have provided a user-defined conversion fromB
toint
. According to 12.3.4 of the standard, "at most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value." This is why it is not converted toA
, because that would require two implicit conversions.The rules for determining exactly when this happens are somewhat complicated, so many people advise that you avoid providing user-defined conversions. Another way of defining these is to provide a constructor with one argument; you can add
explicit
to the beginning to avoid it being applied implicitly.When you call
f(b)
, the compiler applies the conversion that you provided to convertb
toint
. If you want to convert it toA
, you'll have to define a conversion fromB
toA
, or apply one of the conversions explicitly, likef(int(b))
orf(A(b))
.