Interview Q&A · C++ · 8 questions in this topic
Virtual Dispatch & vtables — C++ Interview Q&A
How runtime polymorphism is implemented — vtables, vptr, dispatch cost, and when to avoid virtuals. Part of Inheritance & Polymorphism · 213 questions in the C++ bank.
How does virtual dispatch work (vptr and vtable)?
Answer
Each polymorphic class gets a static vtable (array of function pointers, one per virtual). Each object carries a hidden vptr to its class vtable. A virtual call loads the function address through the vptr and jumps — so the dynamic type, not the static type, selects the implementation.
Construction sets the vptr progressively (which is why ctor virtual calls do not reach derived overrides), and the first virtual call pays an extra indirection plus lost inlining.
Key points
- 1vtable — one per class: addresses of that class virtuals.
- 2vptr — one per object: points at its dynamic-class vtable.
- 3call — load through vptr, indirect jump; hence the small cost.
Example
Base* p = new Derived(); p->f(); // loads Derived vtable entry for f through p vptr
💡 Draw the triangle in words — object holds vptr, vptr points at class vtable, vtable points at functions.
What is the cost of a virtual function?
Answer
One hidden pointer per object (typically 8 bytes), one vtable per class, an indirect branch per call (harder for the CPU to predict), and usually no inlining through the virtual call. For most application code this is negligible; for tiny hot inner loops it can dominate — which is why math kernels and embedded code often use templates/CRTP instead.
Devirtualization lets the compiler convert provably-monomorphic virtual calls into direct calls, recovering the cost when the dynamic type is known.
Example
// hot loop: template (devirtualized/inlined) beats virtual dispatch template<class Op> void run(Op op, int* data, int n) { for (int i = 0; i < n; ++i) op(data[i]); }
Why must a polymorphic base class have a virtual destructor?
Answer
Deleting a derived object through a base pointer with a non-virtual destructor runs only the base destructor — derived members leak and the behavior is undefined. A virtual destructor routes destruction through the vtable so the full derived-then-base chain runs.
Rule: any class with a virtual function should have a virtual (possibly defaulted) destructor; classes not meant as bases should not gain virtuals casually because of the vptr cost.
Example
struct Base { virtual ~Base() = default; }; struct Derived : Base { std::string big; }; Base* p = new Derived(); delete p; // full Derived then Base destruction
What is the difference between static and dynamic polymorphism in practice?
Answer
Static (templates, overloads, CRTP, concepts) binds at compile time: fastest, inlineable, but the type set is fixed at build time and errors surface as long template diagnostics. Dynamic (virtuals) binds at runtime: flexible heterogeneous collections and plugins, at the price of indirection and harder inlining.
Guideline: templates for performance-critical generic code with closed type sets; virtuals for runtime-extensible behavior with open type sets.
Example
// static: fast, closed set template<class T> void print_twice(const T& v); // dynamic: flexible, open set struct Shape { virtual void draw() const = 0; }; void render(const std::vector<std::unique_ptr<Shape>>& s);
What is CRTP (Curiously Recurring Template Pattern)?
Answer
CRTP has Derived inherit from Base<Derived>, giving the base compile-time access to the derived type via static_cast — static polymorphism without virtuals. Uses: static interfaces, mixins, compile-time customization, and eliminating per-object vptr overhead.
The cost is complexity, tighter coupling and harder-to-read errors; it fits libraries and performance cores, not every application hierarchy.
Example
template<class D> struct Comparable { bool operator!=(const D& o) const { return !static_cast<const D&>(*this).operator==(o); } }; struct Int : Comparable<Int> { int v = 0; bool operator==(const Int& o) const { return v == o.v; } };
💡 One sentence carries this answer: derived inherits from a base instantiated on itself, enabling static dispatch to derived members.
What is `dynamic_cast` and when does it return null or throw?
Answer
dynamic_cast safely navigates polymorphic hierarchies at runtime using RTTI. Pointer casts return nullptr on failure; reference casts throw std::bad_cast. Downcasting needs a polymorphic base (at least one virtual), and cross-casting works across multiple-inheritance lattices.
It has measurable cost, so hot paths should be redesigned (visitor, variant, or virtual dispatch) rather than chained dynamic_casts.
Example
Base* b = get(); if (auto* d = dynamic_cast<Derived*>(b)) { d->special(); // safe: null-checked }
What is RTTI and should you use it?
Answer
RTTI (Run-Time Type Information) exposes dynamic types via typeid and dynamic_cast. It is occasionally the right tool (plugins, deserialization, debugging), but frequent type-switching usually signals a design smell — virtual dispatch, std::variant + visit, or the visitor pattern express the same intent more extensibly.
Some codebases disable RTTI (-fno-rtti) for size/speed, in which case dynamic_cast and typeid on polymorphic types are unavailable.
Example
#include <typeinfo> void what_is(const Base& b) { if (typeid(b) == typeid(Derived)) { /* exact type match */ } }
💡 Acceptable answer shape: what it is, one legitimate use, and the cleaner alternative you would prefer.
How do virtual functions interact with the object model (size, layout, vptr)?
Answer
Adding the first virtual gives the object a hidden vptr (usually 8 bytes, first in layout), growing sizeof and making the type non-trivially-copyable and non-standard-layout. Further virtuals cost only vtable slots, not per-object size. Multiple/virtual inheritance adds extra vptrs or offsets.
Consequences matter at ABI boundaries and in serialization: never memcpy a polymorphic object, and never assume layout across compilers.
Example
struct NoVirt { int x; }; struct WithVirt { int x; virtual void f(); }; static_assert(sizeof(WithVirt) > sizeof(NoVirt)); // vptr overhead
Recommended resourcesAffiliate links · may earn us a commission