I am trying to understand overloading resolution in C++ through the books listed here. One such example that i wrote to clear my concepts whose output i am unable to understand is given below.
#include <iostream>
struct Name
{
operator int()
{
std::cout<<"Name's int version called"<<std::endl;
return 4;
}
operator float()
{
std::cout<<"Name's float version called"<<std::endl;
return 1.1f;
}
};
int main()
{
double a = Name(); //this works and calls Name's float version. But WHY ISN'T THIS AMBIGIOUS?
long double b = Name(); //this does not work. WHY IS THIS AMBIGIOUS?
bool c = Name(); //this does not work. WHY IS THIS AMBIGIOUS?
return 0;
}
As you can see here the program works when creating double a. But when i try to create objects b and c it gives error.
My questions are:
Why don't we get the ambiguity error for object
a. That is, among the two conversion operators in className, why thefloatversion is chosen over theintversion.Why/how do we get the ambiguity error for object
bwhich is along double. That is just like fora, i suspected that thefloatversion should have been called but instead we get the error. How is this different from thedouble acase above.Why/how do we get the ambiguity error for object
cwhich isbool. In this case, I suspected that theintversion could have been chosen but instead we get an error. How is this different than thedouble aversion which works and usesfloatversion of conversion function.
I just want to understand why/how the first version works but the other two don't.