liveBook · Manning

Dynamic_cast

As explained in 100 C++ Mistakes and How to Avoid Them

dynamic_cast is a C++ run-time checked cast expression for converting within polymorphic class hierarchies or testing such conversions.

dynamic_cast performs a run-time checked conversion from a polymorphic base-class pointer or reference to a derived-class pointer or reference. The base class needs at least one virtual method so the run-time type can be identified. section 5.6

Mistake: treating a base pointer as a derived object without checking. A pointer cast can yield null when the objects are incompatible; a failed reference cast throws an exception. An unchecked or unsuitable cast can compile successfully yet fail during execution. section 5.6

Check the downcast

With polymorphic B and derived D, use D* d = dynamic_cast<D*>(b); then test d before calling derived behavior. If b does not actually refer to D, handle the incompatible downcast instead of dereferencing a null pointer. Prefer redesigning toward polymorphic behavior when possible. section 5.6

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains polymorphic prerequisites, pointer null results, reference exceptions, and runtime failure consequences.
Examples
Uses B and D classes, a base pointer, a checked downcast, and incompatible-downcast handling.
What it assumes
Assumes familiarity with C++ inheritance, base and derived classes, pointers or references, and virtual methods.
What you can do after
Apply dynamic_cast with pointer-result checks and recognize when polymorphic redesign is safer.
How it connects
Connects dynamic_cast to inheritance, polymorphism, virtual methods, downcasting, and C++ casts.

Also explained in

Compare how 2 books explain dynamic_cast →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.