Learning Hub Search Ctrl K

Legacy C++ › 3. Classes and Object-Oriented Programming

RTTI and Casts

typeid, dynamic_cast, static_cast, const_cast and reinterpret_cast.

intermediate #rtti#typeid#dynamic_cast#static_cast#const_cast#reinterpret_cast

Explanation

C++ has four named casts. Prefer them over the C-style cast (T)x, which can do any of them silently and is hard to search for.

Cast Purpose Checked?
static_cast<T>(x) well-defined conversions: numeric, base↔derived (when you know the type) compile time
dynamic_cast<T>(x) safe downcast in a polymorphic hierarchy run time
const_cast<T>(x) add or remove const/volatile compile time
reinterpret_cast<T>(x) reinterpret bits (pointer↔integer, unrelated pointers) none

RTTI (run-time type information) powers dynamic_cast and typeid. It works only for classes that have at least one virtual function. dynamic_cast to a pointer returns null on failure; to a reference it throws std::bad_cast.

Example

#include <iostream>
#include <typeinfo>

class Animal { public: virtual ~Animal() {} };
class Dog : public Animal { public: void bark() { std::cout << "woof\n"; } };
class Cat : public Animal { };

void pet(Animal* a) {
    if (Dog* d = dynamic_cast<Dog*>(a))     // null if a is not really a Dog
        d->bark();
    else
        std::cout << "not a dog: " << typeid(*a).name() << "\n";
}

int main() {
    Dog dog; Cat cat;
    pet(&dog);
    pet(&cat);

    double pi = 3.14159;
    int whole = static_cast<int>(pi);            // 3
    std::cout << whole << "\n";

    const int c = 5;
    const int* pc = &c;
    int* writable = const_cast<int*>(pc);        // legal cast, but writing through it is UB
    (void)writable;

    try {
        Animal& ref = cat;
        Dog& d = dynamic_cast<Dog&>(ref);        // reference form throws
        (void)d;
    } catch (const std::bad_cast&) {
        std::cout << "bad_cast\n";
    }
    return 0;
}

Common pitfalls

  • dynamic_cast on a non-polymorphic type (no virtual functions) is a compile error.
  • Writing to an object that was originally const after const_cast is undefined behavior.
  • reinterpret_cast is non-portable; treat each use as a red flag.
  • typeid(...).name() is implementation-specific (mangled on GCC).
  • Frequent dynamic_cast chains usually signal a missing virtual function. Fix the design.

Legacy vs modern

C++11 adds std::type_index for use in containers and static_assert-based checks; in templates, if constexpr (C++17) and concepts (C++20) replace many run-time type tests.

Exercises

1. Which cast converts Base* to Derived* safely, with a run-time check?

dynamic_cast<Derived*>(basePtr), which yields a null pointer if the object is not a Derived.