OOPortal OOPortal


Inheritance/Polymorphism  «Prev  Next»
Lesson 13 The const_cast and reinterpret_cast operators
Objective Define general form/use of const_cast/reinterpret_cast operators.

Let us 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:
  1. const_cast, which removes the const attribute from a class
  2. reinterpret_cast, which reinterprets bits
  3. 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.

const_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.

reinterpret_cast

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.

reinterpret_cast<type-id>(expression)