skip to content

A C++ damage handler marked noexcept does dynamic_cast<Player&>(*target); what happens when target is a Monster, and when is the reference form right?

level: seniorimportance: should knowfreq 45%

answer

  1. no such thing as a null reference
  2. failure throws std::bad_cast
  3. an exception meets noexcept
  4. must-be versus maybe

basics

~20 s

A failed reference dynamic_cast throws std::bad_cast, and an exception leaving a noexcept function calls std::terminate, so the game aborts. Use the reference form only where a mismatch is a bug and an exception may propagate; use the pointer form for maybe.

solid answer

~40 s

A reference cannot be null, so `dynamic_cast<Player&>(*target)` reports failure by **throwing** an exception that matches a handler of type `std::bad_cast`. In a handler declared `noexcept`, that exception cannot leave the function: when it reaches the `noexcept` boundary, `std::terminate` is called and the process aborts, with libc++ printing `terminating due to uncaught exception of type std::bad_cast`. So the choice is about meaning. The **reference form** says "this must be a Player; anything else is a bug", and fits code where an exception can propagate to someone who handles it. The **pointer form** says "maybe a Player" and fits dispatch over mixed entities. In a `noexcept` handler that can see Monsters, use the pointer form and branch. Neither form protects against a null `target`: `*target` on null is undefined behaviour before the cast runs.

code

cpp · 31 lines
cpp
#include <iostream>
#include <typeinfo>

struct Entity { virtual ~Entity() = default; };
struct Player : Entity { int hp = 100; };
struct Monster : Entity {};

// Assumes every target is a Player: a mismatch is a bug, so the cast throws.
void apply_damage(Entity& target, int dmg) {
    Player& p = dynamic_cast<Player&>(target);   // std::bad_cast on mismatch
    p.hp -= dmg;
}

void apply_damage_noexcept(Entity& target, int dmg) noexcept {
    Player& p = dynamic_cast<Player&>(target);   // a throw here calls std::terminate
    p.hp -= dmg;
}

int main() {
    Player hero;
    Monster orc;
    apply_damage(hero, 10);
    std::cout << "hero hp " << hero.hp << '\n';
    try {
        apply_damage(orc, 10);
    } catch (const std::bad_cast& e) {
        std::cout << "caught bad_cast\n";
    }
    apply_damage_noexcept(orc, 10);              // terminates the program
    std::cout << "never printed\n";
}

go deeper

for a junior

Know that the reference form of dynamic_cast throws std::bad_cast on failure because a reference cannot be null.

for a middle

Explain how the pointer and reference forms differ in failure signal and intent, and how to catch the exception.

for a senior

Diagnose the abort: an exception reaching a noexcept boundary calls std::terminate, and the fix is the pointer form or an upstream routing fix.

for a principal

Set a team convention for which form appears where, including noexcept code and builds without exceptions, and make it a review item.

## Two forms, two failure signals `dynamic_cast` converts pointers and references. With a pointer target, a failed check yields a null pointer. With a reference target, there is no null value to return, so the standard says a failed cast to reference type **throws** an exception of a type that would match a handler of type `std::bad_cast`. Both lvalue references (`Player&`) and rvalue references (`Player&&`) behave this way. | Form | Success | Failure | |---|---|---| | `dynamic_cast<Player*>(e)` | pointer to the `Player` | null pointer | | `dynamic_cast<Player&>(*e)` | reference to the `Player` | throws `std::bad_cast` | `std::bad_cast` is declared in `<typeinfo>` and derives from `std::exception`; its `what()` string is implementation-defined (libc++ returns `std::bad_cast`). ## The scenario: a `noexcept` damage handler Game code often marks hot, simple functions `noexcept`, for example a damage handler called from the physics step: ```cpp void apply_damage_noexcept(Entity& target, int dmg) noexcept { Player& p = dynamic_cast<Player&>(target); p.hp -= dmg; } ``` When a `Monster` reaches it, the cast throws. A `noexcept` function promises not to let exceptions escape, and the language enforces the promise bluntly: when an exception would propagate out of a function with a non-throwing exception specification, `std::terminate` is called. Whether, and how far, the stack is unwound first is implementation-defined. On the build used for the code example, the process aborted with exit status 134 after libc++abi printed: ```plaintext libc++abi: terminating due to uncaught exception of type std::bad_cast: std::bad_cast ``` The same throw from a function without `noexcept` would simply propagate, and a caller with `catch (const std::bad_cast&)` could recover; the code example does that first and prints `caught bad_cast`. ## Choosing the form The two forms encode different intentions: - **Pointer form: "maybe".** The code expects mixed types and handles the non-matching case as a normal branch: `if (auto* p = dynamic_cast<Player*>(&target)) { ... }`. This is right for dispatch over an entity list. - **Reference form: "must".** The code has an invariant, such as "only players reach the inventory screen", and a mismatch means a bug. Throwing makes the bug loud instead of letting a null pointer travel further. This fits code where exceptions are allowed and someone up the stack logs and recovers. - **Neither, if the type is guaranteed.** When a separate invariant already guarantees the type, the check buys nothing, and a cheaper, unchecked conversion is the usual choice. For the `noexcept` damage handler that may receive Monsters, the pointer form with an explicit branch is correct. If Monsters should never get there, the right fix is upstream, where the handler is registered, not a cast that turns a routing bug into a process abort. ## Handling it well where exceptions are allowed - Catch by const reference, `catch (const std::bad_cast& e)`, never by value, so a derived exception type is not sliced. - Log what actually arrived, for example `typeid(target).name()`, demangled on GCC and Clang, so the routing bug can be found. - Catch at the level that can decide what to do: skip the event, drop the entity or fail the request. Catching right next to the cast and ignoring the error is just the pointer form written expensively. - `std::bad_cast::what()` returns an implementation-defined string, so do not match on its text. ## Null is a separate problem The reference form does not make null safe. In `dynamic_cast<Player&>(*target)`, the expression `*target` dereferences the pointer first; if `target` is null, that is **undefined behaviour** before `dynamic_cast` ever runs. Contrast `typeid(*target)`, which the standard specifically defines to throw `std::bad_typeid` for a null polymorphic pointer. Check the pointer, or use the pointer form, which defines null in as null out. ## Builds without exceptions Some codebases compile with exceptions disabled. There, a failing reference cast cannot throw a catchable exception, so the reference form is effectively a crash on mismatch; such codebases usually forbid it and use the pointer form. How such builds are configured belongs to the material on restricted builds. ## Review checklist 1. Every reference-form `dynamic_cast` sits in code where an exception may escape, or is wrapped in a `try` that catches `std::bad_cast`. 2. No reference-form cast appears in a `noexcept` function, a destructor, or a callback invoked from code that cannot unwind. 3. The pointer form's result is always tested before use.

  • In C++, does catching std::exception also catch the exception thrown by a failed reference dynamic_cast?
    Yes. The thrown object matches a handler of type `std::bad_cast`, and `std::bad_cast` derives publicly from `std::exception`, so `catch (const std::exception&)` catches it too. Catch `std::bad_cast` specifically when you want to treat a type mismatch differently from other failures, and catch by const reference to avoid slicing.
  • Why doesn't dynamic_cast<Player&>(*target) in C++ protect against a null target?
    The operand is `*target`, which dereferences the pointer before the cast is evaluated. Dereferencing a null pointer is undefined behaviour, so the program is already broken when `dynamic_cast` receives its operand. Unlike `typeid`, which has a special rule to throw `std::bad_typeid` for that case, `dynamic_cast` has none. Test the pointer, or use the pointer form, which maps null to null.

The pointer form is asking a crowded room whether anyone is a doctor: silence is a normal answer and you carry on. The reference form is paging the surgeon on call: no answer means something is broken and an alarm goes off. A noexcept function is a room where the alarm cannot be heard, so the building shuts down instead.

  • A failed reference dynamic_cast returns a null reference.
  • An exception thrown inside a noexcept function is silently swallowed.
  • The reference form is the safer choice for mixed entity lists.
  • dynamic_cast<Player&>(*p) throws std::bad_cast when p is null.
  • std::bad_cast is unrelated to std::exception and needs its own handler.