In C++, a Player derives from Renderable and Collidable; can dynamic_cast turn a Renderable* into a Collidable*, and when does it yield nullptr?
answer
- sideways, not down
- the complete object is consulted
- public and unambiguous only
- void* finds the whole object
basics
~20 sYes. A cross-cast asks the complete object for a public, unambiguous Collidable base and returns a pointer to it. It yields nullptr when there is no such base, when it is private or ambiguous, or when the input is null.
solid answer
~40 s`Renderable` and `Collidable` are unrelated classes, so `static_cast` between them does not compile. `dynamic_cast<Collidable*>(r)` can, provided `Renderable` is polymorphic: it finds the **most derived object** that `r` points into, and if that object has a **public, unambiguous** `Collidable` base, it returns a pointer to that subobject, with the address adjusted. It returns **nullptr** when the object has no `Collidable` base (a `Decal` that is only `Renderable`), when `Collidable` is a **private** base, when the object holds **two** `Collidable` subobjects so the target is ambiguous, or when `r` is null. Related: `dynamic_cast<void*>(r)` returns the address of the most derived object, the right tool to check whether two base pointers refer to the same entity. During construction, the dynamic type is the class being constructed, so such casts see only the part already built.
code
cpp · 26 lines#include <iostream>
struct Renderable { virtual ~Renderable() = default; };
struct Collidable { virtual ~Collidable() = default; float radius = 1.0f; };
struct Player : Renderable, Collidable {};
struct Decal : Renderable {}; // drawn, never collides
void collide_if_possible(Renderable* r) {
// Renderable and Collidable are unrelated types: only dynamic_cast can cross.
if (auto* c = dynamic_cast<Collidable*>(r))
std::cout << "collidable, radius " << c->radius << '\n';
else
std::cout << "not collidable\n";
}
int main() {
Player hero;
Decal blood;
collide_if_possible(&hero);
collide_if_possible(&blood);
Renderable* r = &hero;
Collidable* c = &hero;
std::cout << (dynamic_cast<void*>(r) == dynamic_cast<void*>(c)) << '\n';
std::cout << (dynamic_cast<void*>(c) == static_cast<void*>(&hero)) << '\n';
}go deeper
Know that dynamic_cast can move sideways between two bases of the same object, and that the pointer form returns null when it cannot.
Explain why static_cast cannot cross-cast, and list the null cases: missing, private, ambiguous base, or null input.
Use dynamic_cast<void*> for identity, recognise the construction-time failure in registration code, and judge when a stored pointer beats a repeated cross-cast.
Treat frequent cross-casts as a signal about subsystem boundaries, and decide whether the entity model should expose capabilities explicitly.
## Down, up and across In a game, a `Player` may be several things at once: something the renderer draws and something the physics system collides. ```cpp struct Renderable { virtual ~Renderable() = default; }; struct Collidable { virtual ~Collidable() = default; float radius = 1.0f; }; struct Player : Renderable, Collidable {}; struct Decal : Renderable {}; // drawn, never collides ``` The renderer holds `Renderable*`. When it needs to ask "can this thing also collide?", it wants a `Collidable*` to the same object. That conversion is neither up nor down the hierarchy but **across** it, between two bases of a common derived class: a **cross-cast**. ## Why only `dynamic_cast` can do it `Renderable` and `Collidable` are unrelated types; nothing in their declarations connects them. `static_cast` works from declarations alone, so it rejects the conversion: Clang reports `static_cast from 'Renderable *' to 'Collidable *', which are not related by inheritance, is not allowed`. A `reinterpret_cast` would compile but would not adjust the address to the `Collidable` subobject, which sits at a different offset, so using the result would be undefined behaviour. `dynamic_cast` works from the object. The standard describes its run-time check in two steps: 1. If the pointer refers to a public base subobject of a `Collidable` object, and only one such `Collidable` object is derived from that subobject, the result points to it. This is the downcast case. 2. Otherwise, if the pointer refers to a public base subobject of the **most derived object**, and that most derived type has a public, **unambiguous** base of type `Collidable`, the result points to that base subobject. This is the cross-cast case. 3. Otherwise the check fails: null for a pointer, `std::bad_cast` for a reference. The source type, `Renderable`, must be polymorphic, since the check needs the dynamic type. ## When it returns null | Situation | Result | |---|---| | object is a `Player`, `Collidable` a public base | pointer to the `Collidable` subobject | | object is a `Decal`, no `Collidable` base | null | | `Collidable` is a **private** base of the object | null | | object has **two** `Collidable` subobjects | null (ambiguous) | | the `Renderable*` is null | null | Two rows deserve emphasis because they fail at **run time**. Accessibility and ambiguity of an up-conversion are compile-time errors when the compiler can see them, but in a cross-cast the most derived type is only known at run time, so a private or ambiguous target simply makes the check fail. A quick run with a `Boss` holding two `Entity` subobjects, cast from an unrelated third base, printed a null result. ## `dynamic_cast<void*>`: the identity of the whole object Casting to `void*` (for a polymorphic source) returns a pointer to the **most derived object**. Two base pointers into the same entity, a `Renderable*` and a `Collidable*`, hold different addresses, yet their `dynamic_cast<void*>` results are equal. The code example prints `1` for that comparison. Use it for identity checks and for keys in a "seen" set when the same entity may arrive through different interfaces. ## During construction and destruction While a base-class constructor or destructor runs, the object's dynamic type is that base class. A `dynamic_cast` from a pointer to the object, made inside `Renderable`'s constructor while a `Player` is being built, cannot reach `Collidable`: the `Player` does not exist yet. Registration code that cross-casts `this` from a base constructor, for example to add the object to a physics world, therefore fails silently. A run of a similar case, casting `this` to the derived class inside the base constructor, printed a null result. ## Design note A cross-cast in an entity system often means one subsystem is asking another subsystem's question. If many places need it, consider storing the `Collidable*` when the entity is created, or giving the shared base a virtual function that returns it. Those alternatives avoid repeated run-time checks and make the relationship explicit.
- Why does C++ report a private target base as a null result in a cross-cast but as a compile error in an upcast?In an upcast, the compiler sees the derived type and its base list, so an inaccessible base is diagnosed at compile time. In a cross-cast, the compiler sees only `Renderable*`; the type that might derive from both is discovered at run time. The standard's run-time check accepts only public, unambiguous bases, so a private `Collidable` simply makes the check fail and the pointer form returns null.
- In C++, how do you check whether a Renderable* and a Collidable* point into the same object?Compare `dynamic_cast<void*>(r) == dynamic_cast<void*>(c)`. Each returns the address of the most derived object the pointer refers into, so the results are equal exactly when both pointers belong to the same object, even though the two base subobjects sit at different addresses. Both source types must be polymorphic.
- static_cast can convert between two bases of the same derived class.
- dynamic_cast can only move down a single inheritance chain.
- A private target base makes the cross-cast fail to compile.
- Two base pointers into one object always hold the same address.
- A cross-cast from a base constructor already sees the derived class.