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 thefloat
version is chosen over theint
version.Why/how do we get the ambiguity error for object
b
which is along double
. That is just like fora
, i suspected that thefloat
version should have been called but instead we get the error. How is this different from thedouble a
case above.Why/how do we get the ambiguity error for object
c
which isbool
. In this case, I suspected that theint
version could have been chosen but instead we get an error. How is this different than thedouble a
version which works and usesfloat
version of conversion function.
I just want to understand why/how the first version works but the other two don't.
c
case does not work, as it is narrowing, but I'm not sure whya
is allowed andb
is not. – Illyeslanguage-lawyer
tag on this question, if you want the technical answer from the standard citing chapter & verse. – Lidstonefloat
todouble
is a reason,operator float()
returns double. – Dottiedottleoperator char()
instead ofoperator int()
:int b = Name();
- ok,long c = Name();
- ambiguous.char
is promoted toint
andoperator char()
returnsint
. – Dottiedottle