Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 171 ยท Object-Oriented Programming

RTTI, dynamic_cast and typeid

Learn C++ RTTI - dynamic_cast with pointers and references, cross casts, typeid and type_info, the four C++ casts compared, and when type checks are a design smell.

Virtual functions let code call the right behavior without ever asking "what type is this, really?". Occasionally, though, you do need to ask. A plugin system wants to know whether an object also supports an optional interface. A debugger-style tool wants to print an object's real class name. An event handler receives a const Event& and needs the extra fields of a KeyEvent. For these cases C++ offers run-time type information (RTTI): the dynamic_cast operator, which converts a base pointer or reference to a derived one safely, checking at run time, and the typeid operator, which tells you an object's dynamic type.

This lesson shows both, explains how they relate to the other casts (static_cast, const_cast, reinterpret_cast) in one comparison, and ends with the most important part: recognizing when reaching for RTTI means the design should change. You should already know Virtual Functions and Polymorphism and Abstract Classes and Interfaces; the casts were first introduced in Type Conversions and Casts.

dynamic_cast with pointers

dynamic_cast<Derived*>(base_ptr) checks, at run time, whether base_ptr really points to a Derived (or to something derived from Derived). If it does, you get a correctly adjusted Derived*. If it doesn't, you get nullptr. Combined with an if initializer, it reads naturally: "if this event is a key event, then...".

C++ Downcasting safely with dynamic_cast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The DoubleClickEvent is reported as a mouse event, because dynamic_cast<const MouseEvent*> succeeds for any object whose dynamic type is or derives from MouseEvent. That's what you want: dynamic_cast answers "can I treat this as a MouseEvent?", not "is it exactly a MouseEvent?".

The requirements:

  • The source type must be polymorphic: it must have at least one virtual function. A virtual destructor is enough. Without one, dynamic_cast to a derived type doesn't compile, because there's no vtable to carry the type information.
  • dynamic_cast can't remove const. Cast a const Event* to a const KeyEvent*, as above.
  • Casting a null pointer gives a null pointer, so no extra check is needed before the cast.

dynamic_cast with references

References can't be null, so a failed reference cast can't return "nothing". Instead it throws std::bad_cast. Use the reference form when you're confident of the type and a mismatch is a genuine error; use the pointer form when "not that type" is a normal outcome.

C++ A failed reference cast throws bad_cast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The message from what() is implementation-defined; GCC prints std::bad_cast. Exceptions are covered fully in Exceptions.

Cross casts: asking for another interface

dynamic_cast isn't limited to going down a hierarchy. With multiple inheritance it can also go sideways: from one base class to another base class of the same object. This is the classic way to ask "does this object also implement interface X?".

C++ Cross casting between interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

static_cast can't do this: Widget and Clickable are unrelated types, and only a run-time check can discover that one particular Widget happens to be a Button. Notice also that the Clickable* you get back is a different address from the Widget*: the Clickable subobject sits at a different offset inside the Button. dynamic_cast (and static_cast, for related types) adjusts the pointer correctly; reinterpret_cast would not.

A special form, dynamic_cast<void*>(p), returns a pointer to the start of the complete object, whatever base you started from.

typeid and std::type_info

typeid(expression) or typeid(Type) (from <typeinfo>) returns a reference to a std::type_info object describing a type. For a polymorphic object accessed through a reference or a dereferenced pointer, it describes the dynamic type. For anything else it describes the static type, decided at compile time.

C++ typeid, name() and type_index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Things to know about typeid:

  • name() is implementation-defined. GCC and Clang return a mangled name like 3Cat; MSVC returns struct Cat. Never compare names as strings or show them to users unmodified. abi::__cxa_demangle turns GCC/Clang names into readable ones, but it isn't standard C++.
  • Compare type_info objects with ==, not their addresses or names. Use std::type_index when you need a type as a key in a std::map or std::unordered_map.
  • typeid(x) == typeid(Cat) is an exact match: a class derived from Cat would compare unequal. That's usually the wrong question; dynamic_cast answers the more useful "is it at least a Cat?".
  • typeid(*p) with a null pointer to a polymorphic type throws std::bad_typeid.
  • typeid ignores top-level const and references: typeid(const int&) == typeid(int).

The four C++ casts compared

C++ has four named cast operators, each deliberately limited to one kind of conversion so that a cast in code says why it's there. Here they are side by side, with dynamic_cast in context:

Cast Checked when? Use it for Danger
static_cast<T>(x) compile time ordinary conversions (double โ†’ int, enum โ†” int, void* โ†’ T*), upcasts, and downcasts you know are right a wrong downcast is undefined behavior, with no error
dynamic_cast<T>(x) run time downcasts and cross casts on polymorphic types when you're not sure small run-time cost; needs RTTI
const_cast<T>(x) compile time adding or removing const/volatile, usually to call an old API that forgot const modifying an object that was defined const is undefined behavior
reinterpret_cast<T>(x) not at all reinterpreting bits: pointer โ†” integer, unrelated pointer types, viewing an object's bytes almost everything you do with the result besides byte access is undefined behavior

Plus two you should know about:

  • The C-style cast (T)x tries const_cast, static_cast and reinterpret_cast (and combinations) until one compiles. It never does a dynamic_cast. It's dangerous precisely because you can't tell which one you got. Don't use it in C++ code.
  • std::bit_cast<T>(x) (C++20, <bit>) copies the bits of an object into a different type of the same size, the safe replacement for most reinterpret_cast type-punning tricks.
C++ static_cast, const_cast and reinterpret_cast in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every line here is well-defined. The dangerous lines are the ones that compile just as happily: static_cast<Derived&>(unknown).extra would compile and then read memory that isn't part of any Derived (undefined behavior), and writing through the const_cast pointer into a string literal would crash or corrupt memory. When you see a cast in code review, ask which of the four it is and whether it's justified.

When RTTI is a design smell

Here's a pattern that should make you pause:

C++
double area(const Shape& shape) {
    if (auto* c = dynamic_cast<const Circle*>(&shape)) {
        return 3.14159 * c->radius * c->radius;
    }
    if (auto* r = dynamic_cast<const Rectangle*>(&shape)) {
        return r->width * r->height;
    }
    return 0;        // a new shape type silently ends up here
}

This is a hand-written type switch. Every time someone adds a Triangle, they must find and update every such function, and the compiler won't remind them. The object-oriented fix is to move the behavior into the classes, as a virtual function: virtual double area() const = 0;. Then each class answers for itself, and adding a type means adding one class.

If, instead, the set of types is closed (you know them all, like the shapes in a drawing file format) and it's the set of operations that keeps growing, consider std::variant<Circle, Rectangle, Triangle> with std::visit. The compiler then checks that every visitor handles every alternative. See std::optional, std::variant, std::any and std::expected.

dynamic_cast is a reasonable tool when:

  • you're querying an optional capability (the cross cast to Clickable above), especially across plugin or library boundaries,
  • you're writing tooling or debugging code where the real type genuinely matters,
  • an external framework hands you base-class pointers and gives you no better hook.

Two practical notes. First, dynamic_cast isn't free: it walks the type hierarchy at run time, which takes noticeably longer than a virtual call, especially in deep or multiple-inheritance hierarchies. Second, some codebases (many game engines, some embedded projects) compile with -fno-rtti to save space. Then dynamic_cast and typeid on polymorphic objects don't compile, and such projects usually store their own type tags instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Event* e points to a MouseEvent. What does dynamic_cast<KeyEvent*>(e) return?

    A failed dynamic_cast to a pointer type returns nullptr. Only the reference form throws std::bad_cast.
  2. 2. DoubleClick derives from MouseEvent. For a DoubleClick object accessed through Event& e, which expression is true?

    typeid compares exact dynamic types (DoubleClick is not MouseEvent), while dynamic_cast succeeds for any object that is or derives from the target type.
  3. 3. Base has no virtual functions. What happens with dynamic_cast<Derived*>(base_ptr)?

    Downcasting with dynamic_cast needs run-time type information, which only exists for classes with at least one virtual function.
  4. 4. Which cast should you use to call an old function void print(char* s) that doesn't modify s, when you only have a const char*?

    const_cast is the only named cast that can remove const. It's safe here because the function doesn't modify the characters.
  5. 5. A function uses a chain of dynamic_casts to compute a different price for each Product subclass. What's usually the better design?

    A type switch has to be updated for every new subclass, and the compiler won't warn when one is missing. A virtual function puts the behavior in each class.

Summary

  • RTTI gives polymorphic objects (classes with at least one virtual function) run-time type information, used by dynamic_cast and typeid.
  • dynamic_cast<Derived*>(p) returns nullptr when the object isn't a Derived; dynamic_cast<Derived&>(r) throws std::bad_cast. Both accept classes derived from the target.
  • dynamic_cast also performs cross casts between bases of the same object, the standard way to query an optional interface.
  • typeid returns a std::type_info for the exact dynamic type. Compare with ==, use std::type_index as a map key, and don't rely on name() (it's mangled on GCC/Clang).
  • static_cast is for checked-at-compile-time conversions and known-correct downcasts, const_cast adds or removes const, reinterpret_cast reinterprets bits, and std::bit_cast does type punning safely. Avoid C-style casts.
  • A chain of dynamic_casts or typeid checks is usually a missing virtual function, or a job for std::variant.

Next: Structs, Aggregates and Unions, the simplest user-defined types and how they're initialized.