[ fromfile: types.xml id: typecast ]
Explicit conversions are called casts. Casting is sometimes necessary but it tends to be overused and can be a major source of errors. 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
For example:
double d=3.14; int i = (int)d;
C++ also supports an alternative 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);
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |