Sobes.tech
Junior — Middle

What is the difference between static_cast, dynamic_cast, and reinterpret_cast in C++?

sobes.tech AI

Answer from AI

In C++, there are different types of casting, each serving its own purpose:

  • static_cast — used for explicit type conversions checked at compile time. Suitable for conversions between compatible types, such as from int to float or from a base class to a derived class (without runtime checks).

  • dynamic_cast — used for safe casting of pointers or references within an inheritance hierarchy. Works only with polymorphic types (with virtual methods). Returns nullptr (for pointers) or throws an exception (for references) on failure. Used for runtime type checking.

  • reinterpret_cast — the most "rigid" and unsafe cast, which simply interprets the bit pattern of an object as another type. Used for low-level operations, such as converting a pointer to an integer type and back. Requires caution, as it can lead to undefined behavior.

Example:

class Base { virtual void foo() {} };
class Derived : public Base {};

Base* b = new Derived();

// static_cast: no runtime check
Derived* d1 = static_cast<Derived*>(b);

// dynamic_cast: with runtime check
Derived* d2 = dynamic_cast<Derived*>(b);

// reinterpret_cast: simply changes the pointer interpretation
intptr_t ptr_val = reinterpret_cast<intptr_t>(b);
What is the difference between static_cast… - sobes.tech