skip to content

OOP and Polymorphism

Virtual functions, vtables, multiple inheritance and RTTI are C++'s runtime polymorphism, and each has a cost. Interviewers ask about virtual destructors, slicing and the diamond.

on this pageshow

explore

questions

22

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.
open as a page

In C++, what do the override and final specifiers do on a virtual member function, and which bug does override catch?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Since C++11, override asks the compiler to prove that a member function overrides a base virtual; if it does not, the program is ill-formed. final forbids further overriding of a function, or any derivation from a class.

open as a page

In C++, what goes wrong when you delete a derived Reverb object through an Effect* whose destructor is not virtual?

level: juniorimportance: must knowfreq 82%

basics

~20 s

The delete has undefined behaviour. In practice compilers usually call only ~Effect, so ~Reverb and the destructors of Reverb's members never run and whatever they own leaks. Declaring virtual ~Effect() = default in the base fixes it.

open as a page

In C++, if InputStream and OutputStream both inherit StreamBase non-virtually, what does an IOStream deriving from both contain, and what breaks?

level: middleimportance: must knowfreq 65%

basics

~20 s

IOStream contains two separate StreamBase subobjects, one per path. Unqualified use of a StreamBase member and conversion to StreamBase* are ambiguous, and the two copies can drift apart. Virtual inheritance in InputStream and OutputStream makes them share one.

open as a page

In C++, what happens when a Reverb object is stored in a std::vector<Effect> or passed to a function taking Effect by value?

level: middleimportance: must knowfreq 70%

basics

~10 s

The Reverb is sliced: Effect's copy constructor builds a brand-new Effect from the Effect part of the Reverb, so Reverb's data is lost and virtual calls on the copy run Effect's functions, not Reverb's.

open as a page

How do mainstream C++ compilers implement a virtual call through a Body&, and what does the C++ standard itself require of that mechanism?

level: middleimportance: must knowfreq 75%

basics

~20 s

The standard requires only that a virtual call run the final overrider for the object's dynamic type. Compilers use a per-class vtable of function pointers and a hidden per-object vptr: load the vptr, load a fixed slot, branch indirectly.

open as a page

In C++, how does a Button class inherit from both Drawable and Clickable interfaces, and what makes it instantiable?

level: juniorimportance: should knowfreq 55%

basics

~10 s

List both bases, each with its own access specifier: class Button : public Drawable, public Clickable. Button stays abstract, and cannot be instantiated, until it overrides every pure virtual function inherited from both bases.

open as a page

In C++, why does adding a virtual function to a struct with one float grow sizeof from 4 to 16 on 64-bit targets?

level: juniorimportance: should knowfreq 62%

basics

~20 s

Mainstream ABIs add a hidden vtable pointer to every polymorphic object: 8 bytes on a 64-bit target. The struct's alignment becomes 8, so 8 + 4 bytes round up to 16. More virtual functions add no further per-object size.

open as a page

Why does C++ reject dynamic_cast<Player*>(e) when Entity has no virtual functions, and what does typeid(*e) report then?

level: middleimportance: should knowfreq 45%

basics

~20 s

A downcast with dynamic_cast needs a polymorphic source type, one with at least one virtual function, because only then can the object's dynamic type be found at run time. For a non-polymorphic Entity, typeid(*e) reports the static type, Entity.

open as a page

In C++, why does typeid(*entity).name() print something like 6Player, and how should code compare or key on dynamic types?

level: middleimportance: should knowfreq 40%

basics

~10 s

std::type_info::name() returns an implementation-defined string; GCC and Clang return the mangled name, so Player prints as 6Player. Compare types with type_info's operator== and key containers with std::type_index, never with name() strings.

open as a page

In C++, what makes a class abstract, can a pure virtual function have a definition, and why must a pure virtual destructor be defined?

level: middleimportance: should knowfreq 55%

basics

~20 s

A class is abstract while some pure virtual function, declared with = 0, is still its final overrider. A pure virtual may have a body, reached by qualified call, and a pure virtual destructor must be defined because derived destructors call it.

open as a page

Why does linking a C++ program fail with an undefined vtable for Body when Body's constructor and other members compile fine?

level: middleimportance: should knowfreq 45%

basics

~20 s

Under the Itanium C++ ABI, Body's vtable is emitted only in the translation unit that defines its key function, the first non-inline, non-pure virtual function. If that function is never defined or its file is not linked, no vtable exists.

open as a page

Why can converting a C++ Button* to its second base Clickable* change the address, and how does that break a void* callback?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Each base is a subobject at its own offset inside Button, so a Clickable* may point past the Button's start. A void* round trip skips that adjustment: a pointer stored as Button* must come back as Button*, never straight as Clickable*.

open as a page

In a C++ diamond with a virtual StreamBase, why is InputStream's StreamBase(fd) initializer ignored when an IOStream is constructed?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A virtual base is constructed once, by the most derived class. InputStream's and OutputStream's StreamBase initializers are skipped; IOStream's own initializer is used, or StreamBase's default constructor if IOStream names none, and compilation fails when there is none.

open as a page

A profiler flags dynamic_cast inside a C++ entity update loop; what makes the check costly, and what replaces it when RTTI is unavailable?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A checked downcast is usually a runtime-library call that walks the dynamic type's inheritance description, slower with deep or multiple inheritance. Replace it with a virtual function, a type tag, std::variant, or typed pointers stored once at spawn time.

open as a page

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%

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.

open as a page

In C++, an Effect constructor calls the virtual reset() that Delay overrides; which reset() runs, and what changes if reset() is pure virtual?

level: seniorimportance: should knowfreq 60%

basics

~10 s

Effect::reset runs, not Delay::reset: during Effect's constructor and destructor a virtual call resolves to the final overrider in Effect itself. If that function is pure, the call is undefined behaviour, often an abort.

open as a page

When can a C++ compiler turn a virtual update() call into a direct call, and why does marking Particle final not help calls through Body&?

level: seniorimportance: should knowfreq 45%

basics

~20 s

When it can prove the override (final static type, visible dynamic type, one implementation program-wide) or guards a guess with a runtime check. Through Body&, final on Particle proves nothing: any class derived from Body could be there.

open as a page

A profiler flags a C++ physics loop calling virtual update() on 100,000 bodies each frame; what does each call really cost, and how do you cut it?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Each call loads the object's vptr, often a cache miss when bodies are scattered on the heap, then makes an indirect branch that mispredicts when types interleave, and blocks inlining. Group bodies by type and dispatch once per batch.

open as a page

As a C++ lead, would you restrict multiple inheritance to interface-style abstract bases, and which exceptions would your team's rule allow?

level: principalimportance: should knowfreq 30%

basics

~20 s

Usually yes as the default: any number of pure interface bases, at most one base that carries state or implementation, and virtual inheritance only after review. Allow named exceptions, such as empty tag or policy bases and established library types like std::enable_shared_from_this.

open as a page

In a C++ audio plugin framework whose virtual Effect::process() runs per sample, how do you decide between keeping it virtual and moving to std::variant or templates?

level: principalimportance: should knowfreq 40%

basics

~20 s

Decide by who extends the set and where the cost really is. Third-party effects loaded at run time need a virtual interface; a closed built-in set can be a std::variant; a fixed chain can be templates. Often process() per block fixes it.

open as a page

In C++, a Player derives from Renderable and Collidable; can dynamic_cast turn a Renderable* into a Collidable*, and when does it yield nullptr?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Yes. 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.

open as a page