Different Casts in Cpp

Here are usage examples for each C++ cast operator:

1. const_cast

Used to add or remove const/volatile qualification. It should only be used when you are certain the original object is not actually const (e.g., modifying a value that came from a non‑const variable but is currently accessed through a const pointer).

void modify(const int* p) {
    // p points to a const int, but we know the original int is non-const
    int* modifiable = const_cast<int*>(p);
    *modifiable = 42;   // OK only if the original object was non-const
}

int main() {
    int x = 10;
    modify(&x);        // x is non-const, so modification is safe
    // const int y = 20;
    // modify(&y);     // Would be undefined behavior (modifying a truly const object)
}

2. static_cast

Performs well‑defined conversions between related types at compile time. Common uses include numeric conversions, upcasting, and explicit downcasting when you are sure of the type.

// Numeric conversion
double pi = 3.14159;
int intPi = static_cast<int>(pi);        // Truncates to 3

// Upcasting (derived to base) – usually implicit, but explicit is fine
class Base {};
class Derived : public Base {};
Derived d;
Base* bp = static_cast<Base*>(&d);       // Safe upcast

// Downcasting (base to derived) – unchecked, user must ensure correctness
Base* b = new Derived();
Derived* dp = static_cast<Derived*>(b);  // OK because b really points to Derived
// If b pointed to a pure Base object, this would be undefined behavior

3. reinterpret_cast

Performs low‑level, type‑unsafe reinterpretation of bit patterns. Typically used for casting between unrelated pointer types, or between pointers and integers.

4. dynamic_cast

Performs a runtime‑checked downcast (or cross‑cast) in polymorphic hierarchies. Requires at least one virtual function in the base class. Returns nullptr for pointers (or throws std::bad_cast for references) if the cast fails.

Each cast has its purpose: const_cast for qualifier adjustment, static_cast for compile‑time checked conversions, reinterpret_cast for bit‑level reinterpreting, and dynamic_cast for runtime‑checked type-safe downcasting.

Last updated