Converting from user defined variable to basic type:
(All the below things are written wrt Robert Lafore's Book on C++)
If I have a user defined variable(say Userval,it is the name of the class and its object is userval1) and a float variable (say meters)
Is it correct to write in main the statement
meters=static_cast<float>(userval1);
and the conversion operator will be written in the Class definition(here, in the definition of Userval)
operator float()const
{
//some specific statements
}
My question is
if we just write
meters=userval2;
then how come the compiler knows that it has to refer the conversion operator float()
may be my way of asking make the question complicated but I hope you will be able to help me..
meters=userval2; is an assignment expression. The type of the left operand is non-class (float) and the type of the right operand is a class type (Userval). The C++ language says that, in this specific case, the compiler must find (and compile) a valid implicit conversion sequence that leads from Userval to float. User-defined conversion member functions, such as the one you wrote, are included in the search in this case. It's just a language rule.
Cubbi is correct. C++ has some very complicated rules regarding casts; the basic idea is that if there is a type mismatch, the compiler will try to find some combination of casts to make it work. In your example, the float cannot cast, as it represents a physical storage space (it is an lvalue, to be precise), while the Userval can cast as its value is being used (it is an rvalue).
These cast rules can be used to do very elegant things, or they can be another way to shoot yourself in the foot. Be careful not to overuse implicit cast operators, as you increase the chance that you will accidentally use the wrong type as some parameter and the compiler will accept it.
it is no where mentioned that it will take userdefined variable(here Userval) as the arguement. when we write simply
meters=userval2;
what statements in the definition help the compiler to decide that "yes,this is the conversion operator i am looking for converting a Userval to float (in this case float())"
shouldn't we write it as
operator float(Userval)const
{
//some specific statements
}