skip to content

In C++, what does dynamic_cast<Player*>(entity) return when the Entity* does not point to a Player?

level: juniorimportance: must knowfreq 70%

answer

  1. a checked downcast
  2. the object's actual type decides
  3. failure is a null pointer
  4. test it in the if condition

basics

~20 s

It returns a null pointer. dynamic_cast checks the object's actual type at run time and yields a Player* only when the object really is a Player (or derives from it); a null input also yields null.

solid answer

~40 s

`dynamic_cast<Player*>(e)` is a **checked downcast**. At run time it looks at the object `e` points to: if that object is a `Player`, or a class derived from `Player`, the result points to it; otherwise the result is a **null pointer**. A null `e` gives a null result too. So the idiomatic use tests the result before touching it: `if (auto* p = dynamic_cast<Player*>(e)) { p->score += 10; }`. The check needs `Entity` to be polymorphic, which in practice means a virtual destructor. Contrast `static_cast<Player*>(e)`, which performs no check and gives undefined behaviour when the object is not a `Player`. The reference form, `dynamic_cast<Player&>(*e)`, cannot return null, so it throws `std::bad_cast` instead.

code

cpp · 25 lines
cpp
#include <iostream>

struct Entity {
    virtual ~Entity() = default;   // makes Entity polymorphic
};
struct Player : Entity { int score = 0; };
struct Monster : Entity {};

void reward(Entity* e) {
    // dynamic_cast checks the object's actual type at run time.
    if (auto* p = dynamic_cast<Player*>(e)) {
        p->score += 10;
        std::cout << "player, score " << p->score << '\n';
    } else {
        std::cout << "not a player\n";   // a Monster, or a null pointer
    }
}

int main() {
    Player hero;
    Monster orc;
    reward(&hero);
    reward(&orc);
    reward(nullptr);
}

go deeper

for a junior

Say it plainly: a failed pointer dynamic_cast returns null, a null input returns null, and the result is tested before it is used.

for a middle

Explain dynamic type versus static type, why the base must be polymorphic, and the contrast with the unchecked static_cast.

for a senior

Discuss when a downcast signals a design smell, and when a checked cast at a system boundary is the honest tool.

for a principal

Relate the pattern to how an entity system dispatches behaviour, and when a team should prefer virtual functions or variants over downcasts.

## What a downcast is In a game, an entity system usually stores every object through a base-class pointer: a `std::vector<Entity*>` holds players, monsters, pickups and props alike. A **downcast** converts a pointer to the base (`Entity*`) into a pointer to a more derived class (`Player*`), so code can reach members only `Player` has, such as a score. The danger is obvious: the pointer may not point to a `Player` at all. C++ offers a downcast that **checks**, `dynamic_cast`, and one that **trusts you**, `static_cast`. ## What `dynamic_cast<Player*>` returns For a pointer target type, `dynamic_cast` has three outcomes: | What `e` points to | Result of `dynamic_cast<Player*>(e)` | |---|---| | a `Player` | a `Player*` to that object | | an object of a class derived from `Player` | a `Player*` to its `Player` part | | a `Monster`, or any other non-`Player` object | a null pointer | | nothing (`e` is null) | a null pointer | The standard words the failure case directly: the value of a failed cast to pointer type is the null pointer value of the required result type. Nothing is thrown, nothing is logged; the null pointer *is* the answer to "is this a Player?". ## The idiom Because the failure value is null, the result goes straight into a condition: ```cpp if (auto* p = dynamic_cast<Player*>(e)) { p->score += 10; } ``` The variable `p` exists only inside the `if`, so it cannot be used unchecked afterwards. The code example rewards three inputs and prints `player, score 10`, then `not a player` for the `Monster`, then `not a player` for the null pointer. Common mistakes: - **Using the result without testing it.** `dynamic_cast<Player*>(e)->score` dereferences null when the object is a `Monster`, which is undefined behaviour. - **Testing the wrong thing.** Checking `e != nullptr` says nothing about whether the object is a `Player`. - **Assuming exact-type matching.** A `Boss` that derives from `Player` passes the check; `dynamic_cast` answers "is-a", not "is exactly". ## What it requires The run-time check needs to know the object's **dynamic type**, the type of the complete object it is part of. C++ only guarantees that information for **polymorphic** classes, classes with at least one virtual member function. In practice `Entity` gets a virtual destructor, which it needs anyway if entities are ever deleted through `Entity*`. Without one, the downcast does not compile; that requirement has its own question in this lesson. ## Where the result points, and what it keeps - **The address may change.** On success the result points to the `Player` part of the object. When `Player` has several bases, that part need not start at the same address as the `Entity` part, and `dynamic_cast` applies the offset for you. - **Constness is kept.** `dynamic_cast` may not cast away `const`. From a `const Entity*`, ask for a `const Player*`; asking for `Player*` fails to compile, and Clang says the cast `casts away qualifiers`. - **It answers for this moment.** The result is a plain pointer: it does not keep the object alive. If the entity is destroyed later in the frame, the `Player*` dangles like any other raw pointer. ## Compared with `static_cast` `static_cast<Player*>(e)` compiles to plain pointer arithmetic with no run-time check. When `e` really points to a `Player`, it is correct and cheaper. When it does not, the result is a pointer that only looks valid, and using it is undefined behaviour. Choose `dynamic_cast` when the type is genuinely unknown at that point in the code, and `static_cast` only when some other invariant already guarantees the type. ## The reference form, briefly `dynamic_cast` also converts references: `dynamic_cast<Player&>(*e)`. A reference cannot be null, so a failed reference cast throws an exception matching `std::bad_cast` instead. Pointer form for "maybe a Player", reference form for "must be a Player, or it is a bug". The consequences of that throw, especially in `noexcept` code, are covered in their own question. ## How interviewers ask it 1. "What does `dynamic_cast` return on failure?" expects "null for pointers, `std::bad_cast` for references". 2. "Why would you use it instead of `static_cast`?" expects "it checks the dynamic type". 3. "What does the base class need?" expects "at least one virtual function".

  • Does dynamic_cast<Player*> in C++ succeed for an object of a class derived from Player?
    Yes. The check asks whether the object contains a `Player` it can reach publicly and unambiguously, not whether its type is exactly `Player`. A `Boss` derived from `Player` yields a valid `Player*` to its `Player` part. To test for the exact type instead, compare `typeid(*e) == typeid(Player)`, which is false for a `Boss`.
  • Why is static_cast<Player*>(e) dangerous when e points to a Monster in C++?
    `static_cast` performs no run-time check: it trusts that `e` points to a `Player` and simply adjusts the pointer. If the object is a `Monster`, the result does not point to a `Player`, and reading `score` through it is undefined behaviour, which may appear to work, corrupt memory or crash. `dynamic_cast` would have returned null.

  • A failed dynamic_cast to a pointer type throws std::bad_cast.
  • dynamic_cast succeeds only when the type matches exactly, never for subclasses.
  • Checking e != nullptr first proves the object is a Player.
  • static_cast performs the same run-time check, only faster.
  • A dynamic_cast downcast works on any class, virtual functions or not.