| Lesson 13 || The const_cast and reinterpret_cast operators |
| Objective || Define general form/use of const_cast/reinterpret_cast operators. |
const_cast and reinterpret_cast C++ Operators
Examine the areas of casts and Runtime Type Identification
These topics are essential for writing programs that ensure type safety.
You should already be familiar with the static_cast operator. There are several other casting operators specific to the C++ language which have not been discussed so far in the course:
- const_cast, which removes the const attribute from a class
- reinterpret_cast, which reinterprets bits
- dynamic_cast, is used with classes having virtual functions
We will look at const_cast and reinterpret_cast in this lesson and dynamic_cast in the next lesson.
Use of const_cast and reinterpret_cast is rather dangerous, however these operators are necessary to provide a complete alternative to the old C-style casts. Please note that older compilers may not support the use of reinterpret_cast.
The const_cast operator has the form:
const_cast< type-id >( expression )
The const_cast operator can be used to remove the const attribute from a class. A pointer to any object type can be explicitly converted to a type that is identical except for the const qualifier.
The result of this conversion will refer to the original object.
The reinterpret_cast operator has the form:
The reinterpret_cast operator can be used for conversions such as char* to int*, or any_class* to a completely_different_class*.
These conversions, however, are extremely unsafe.
The safest use for the result of a reinterpret_cast is to cast it back to its original type.