I have a doubt about how C++ casts types when it has to do math.
The code below as it is ( i.e. with only the cast to int without casting to double ) works and builds without problem. If I define ENABLE_DOUBLE_CAST doesn’t build and complains about operator*. Do you know why?
The doubts I have are 2:
- why without the operator cast to double, it is used the one to int in a multiplication between double. Is it because of the implicit cast?
- why WITH the cast to double enable ( adding more clarity to the syntax ) that is not taken into consideration?
Thanks
AFG
class CA{
int _m;
public:
CA( int a, int b ){
_m=a*b;
}
operator int (){
std::cout<< "(CA int cast)" ;
return _m;
}
#ifdef ENABLE_DOUBLE_CAST
operator double(){
std::cout << "(CA double cat)";
return 2.3 * _m;
}
#endif
};
int main( int argc, const char** argv){
CA obj_2( 10,20 );
double total_1 = 100.0 * obj_2;
double total_2 = obj_2 * 100.0;
return 0;
}
why without the operator cast to double, it is used the one to int in a multiplication between double. Is it because of the implicit cast?
Yes that is true.
It uses the
operator int ()to convertobj_2to an int and then uses the inbuiltoperator*(double, int)why WITH the cast to
doubleenabled ( adding more clarity to the syntax ) that is not taken into consideration?When you provide both
operator double()andoperator int ()for your class, it creates an ambiguity, whether to convertobj_2to anintordoublebecause there are two inbuilt operator overloads which it can use, namely:Suggestion:
You should overload the
operator*for your class if you want to avoid this problem of implicit conversions and ambiguity arising over it.