|
|
A cast is a special operator that forces one data type to be converted into another. Both C and C++ support the form of cast shown here:
(type) expression
where type is the desired data type.
For example, the following cast causes the outcome of the specified integer division to be of type double:
double d; d = (double) 10/3;
C++ supports additional casting operators. They are const_cast, dynamic_ cast, reinterpret_cast, and static_cast. Their general forms are shown here:
const_cast<type> (expr) dynamic_cast<type> (expr) reinterpret_cast<type> (expr) static_cast<type> (expr)
Here, type specifies the target type of the cast and expr is the expression being cast into the new type.
The const_cast operator is used to explicitly override const and/or volatile in a cast. The target type must be the same as the source type except for the alteration of its const or volatile attributes. The most common use of const_cast is to remove constness.
dynamic_cast performs a runtime cast that verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression evaluates to null. Its main use is for performing casts on polymorphic types. For example, given two polymorphic classes B and D, with D derived from B, a dynamic_ cast can always cast a D* pointer into a B* pointer. A dynamic_cast can cast a B* pointer into a D* pointer only if the object being pointed to actually is a D object. In general, dynamic_cast will succeed if the attempted polymorphic cast is permitted (that is, if the target type can legally apply to the type of object being cast). If the cast cannot be made, then dynamic_ cast evaluates to null if the cast involves pointers. If it fails on a reference, a bad_cast exception is thrown.
The static_cast operator performs a nonpolymorphic cast. For example, it can be used to cast a base class pointer into a derived class pointer. It can also be used for any standard conversion. No runtime checks are performed The reinterpret_cast operator changes one type into a fundamentally different type. For example, it can be used to change a pointer into an integer. A reinterpret_cast should be used for casting inherently incompatible pointer types.
Only const_cast can cast away constness. That is, neither dynamic_cast, static_cast, nor reinterpret_cast can alter the constness of an object.
|
|