Reputation: 73
In the given code, I am not able to understand why the compiler is producing errors when the function is called. It is passing object of test
class which has its data member of a test2
class
class Test2 {
int y;
};
class Test {
int x;
Test2 t2;
public:
operator Test2 () {return t2;}
operator int () {return x;}
};
void fun (int x) {
cout << "fun(int) called";
}
void fun (Test2 t) {
cout << "fun(Test 2) called";
}
int main() {
Test t;
fun(t);
return 0;
}
Upvotes: 0
Views: 41
Reputation: 26800
The call fun(t);
is ambiguous because both overloads of fun
are eligible for it.
This is again because t
is a Test
object which can be converted to both Test2
and int
.
Marking either one of the conversion operators as explicit
will resolve this issue.
See Demo here.
Upvotes: 0
Reputation: 38267
I am not able to understand why the compiler is producing errors when the function is called
How is the compiler supposed to figure out which function to call? You have two function in the overload set associated with the name func
, and two operators that allow for implicit conversions to types that equally well match both function parameters of this overload set.
The situation is identical to
void f(long);
void f(short);
f(42); // Error: both conversions int -> log and int -> short possible
You can fix it by e.g.
fun(static_cast<Test2>(t)); // be explicit on the calling side
or by marking one (or both) of the conversion operators as explicit
explicit operator Test2 () {return t2;}
which disables implicit conversions to Test2
and requires an explicit cast as shown before.
Upvotes: 1