cpp-static-dynamic-const-cast

Converters static_cast, dynamic_cast and const_cast in C++

  • 6 min

In C++, specific casts are more controlled ways of performing conversions between types. These are static_cast, dynamic_cast, const_cast, and reinterpret_cast.

Each one has its specific purpose

  • static_cast: For conversions between related types without polymorphism
  • dynamic_cast: For safe conversions in polymorphic class hierarchies
  • const_cast: To remove or add const (use with caution ⚠️)
  • reinterpret_cast: Low-level conversions between unrelated types, such as pointers and integers (use with extreme caution ❗)

These allow for safer management of type conversion compared to the “classic” cast operator (dataType)object (especially when working with class hierarchies and inheritance).

Although the (dataType) operator is faster to write, it can be dangerous because it performs no safety checks, which can lead to errors.

Conversion with static_cast

static_cast is used for conversions between related types that can be determined at compile time. This type of cast is very useful for converting between numeric types, as well as in class hierarchies without polymorphism.

You should not use static_cast when polymorphism is involved, as it does not check if the conversion is safe at runtime. Instead, you should use dynamic_cast in these cases.

Conversion with dynamic_cast

dynamic_cast is primarily used when working with class hierarchies that have at least one virtual function (i.e., classes with polymorphism).

This type of cast is the only one that checks the validity of the conversion at runtime, returning nullptr if the conversion is not possible.

  • Do not use dynamic_cast if you can determine the conversion at compile time (use static_cast in those cases).

Conversion with const_cast

const_cast is used to remove or add the const qualifier to an object.

Although it seems useful, modifying an object that was originally declared as const can result in undefined behavior, so it should be used with caution.

  • Avoid modifying objects that were originally declared as const
  • In fact, avoid using it in general 😉

Conversion with reinterpret_cast

reinterpret_cast is the most dangerous cast and is used to perform low-level conversions between pointer types or between pointers and integer data types.

Unlike other types of casts, it performs no safety checks and simply “reinterprets” the bits of the object as the new type.

Basically, reinterpret_cast is similar to the classic cast (dataType).

  • Avoid using it for any type of conversion between classes or data types that are not directly related
  • In fact, avoid using it a lot