Explicit Conversions
Explicit conversions are called casts. Casting is sometimes necessary, but it tends to be overused and can be a major source of errors. In fact, Bjarne Stroupstrup, the creator of C++, is on record recommending that they be used as little as possible.
Because of its roots in the C language, C++ supports the old-style (unsafe) C-style casting (type)expr:
double d=3.14; int i = (int) d;
C++ also supports an alternate constructor-style syntax for casts:
Type t = Type(arglist)
A cast causes a temporary value of the specified type to be created and pushed onto the program stack. If Type is a class, a temporary object is created and initialized by the appropriate conversion constructor. If Type is a native type, Type(arg) is equivalent to (Type) arg. The temporary is kept on the stack just long enough to evaluate the expression it is in. After that, it is destroyed.
For example,
double d = 3.14; Complex c = Complex(d);
Safer Typecasting Using ANSI C++ Typecasts
|