Runtime Polymorphism vs Static Polymorphism in C++
System DesignModel answerLast updated
Describe how virtual functions are typically implemented in C++, then weigh them against CRTP-based static polymorphism and say when each design is the better fit.
You are reviewing the design of a C++ library that needs to support several interchangeable implementations of a common interface (for example, different codecs, shapes, or storage backends).
Answer the following:
- Explain how virtual functions are commonly implemented by compilers. Cover object layout, how a call is dispatched, and what happens with overrides, base-class destructors and multiple inheritance.
- Explain the Curiously Recurring Template Pattern (CRTP) and how it provides polymorphism without virtual calls.
- Compare the two approaches on: runtime flexibility, object layout, separate compilation, heterogeneous collections, inlining, code size, compiler diagnostics, ABI stability across shared libraries, and measured performance.
- Recommend when each is appropriate, and say what you would ask or measure before deciding.
Constraints and assumptions:
- The C++ standard defines the behavior of virtual functions but does not mandate any particular vtable layout. Qualify your description of vptrs and vtables accordingly.
- Your comparison must explicitly address separate compilation and heterogeneous collections.
- Do not claim that a single indirect call is always a meaningful performance cost.
Useful clarifying questions to raise: Is the concrete type chosen at runtime or known at compile time? Do objects cross a stable ABI boundary such as a shared library? Are binary size or build time significant constraints?
Hints
Hint 1
Start with the common implementation (a hidden per-object pointer to a per-class table of function pointers), and state clearly that this is typical practice, not a requirement of the standard.
Hint 2
For CRTP, think about what `static_cast<Derived&>(*this)` allows the compiler to know at compile time, and what that implies for inlining, for storing different types in one container, and for headers.
Hint 3
Frame your final recommendation around the decision factors: is the type known at compile time, is there an ABI boundary, do you need heterogeneous containers or plugins, and what does a benchmark show on the real workload?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
How virtual dispatch is usually implemented
The standard specifies observable behavior (a call through a base reference or pointer runs the final overrider of the dynamic type) but not the mechanism. In practice, mainstream compilers (the Itanium ABI on GCC/Clang, and MSVC with its own variant) do roughly this:
- Each polymorphic class has a vtable: a static, read-only array of function pointers, one slot per virtual function, plus metadata such as RTTI information.
- Each object of a polymorphic class carries a hidden vptr, set by the constructor, that points at the vtable for its dynamic type. This typically adds one pointer (8 bytes on 64-bit) to the object.
- A call
p->f()loads the vptr, loads the slot forf, and performs an indirect call. Slot indices are fixed at compile time. - A derived class that overrides
fplaces its own function in that slot. Non-overridden slots point to the base implementation. - During construction and destruction the vptr is adjusted so that the dynamic type is the class currently being built or torn down. This is why virtual calls in constructors do not reach derived overrides.
- Multiple inheritance can give an object several vptrs and require
this-pointer adjustment thunks. Virtual inheritance adds further indirection through virtual base offsets.
Virtual destructors. If you delete a derived object through a base pointer and the base destructor is not virtual, the behavior is undefined: typically the derived part is never destroyed, leaking resources. Any class intended as a polymorphic base that is deleted through a base pointer needs a virtual destructor (or a protected non-virtual destructor if deletion through the base is forbidden by design).
CRTP
In CRTP a class derives from a template instantiated with itself:
template <class D>
struct Shape {
double area() const { return static_cast<const D&>(*this).area_impl(); }
};
struct Circle : Shape<Circle> {
double r;
double area_impl() const { return 3.14159265 * r * r; }
};
template <class T>
double total(const Shape<T>& s) { return s.area(); }
The base knows the derived type at compile time, so area() resolves statically. There is no vptr, no vtable and no indirect call. The "interface" is an implicit compile-time contract: the derived class must provide area_impl. Since C++20 you can state the contract with a concept.
Comparison
| Aspect | Virtual functions | CRTP |
|---|---|---|
| Binding | Runtime | Compile time |
| Object layout | Extra vptr per object | No overhead; empty bases can be optimized away |
| Heterogeneous collection | Natural: vector<unique_ptr<Base>> | Not directly; Shape<Circle> and Shape<Square> are unrelated types. Needs std::variant, type erasure, or an extra virtual layer |
| Separate compilation | Implementation can live in a .cpp; callers only need the header with the class declaration | Templates generally live in headers; changes recompile all users |
| Inlining | Usually blocked unless the compiler can devirtualize (known final type, final, whole-program or LTO) | Calls are direct and readily inlined, enabling further optimization |
| Code size | One copy of each function | One instantiation per derived type; can bloat the binary |
| Diagnostics | Missing overrides caught at link or class definition (pure virtuals); override helps | Errors appear at instantiation and can be long and cryptic; concepts improve this |
| ABI | A stable vtable layout works across shared-library boundaries and plugins loaded at runtime | Instantiations are compiled into each client, so changes break clients and nothing can be selected at runtime |
| Extensibility | Third parties can add subclasses without recompiling existing code | Types must be known when the template is instantiated |
Performance
A virtual call costs a couple of dependent loads and an indirect branch. When the call target is predictable and the function body is nontrivial, this is often negligible. The larger cost is usually the lost inlining: it blocks constant propagation, vectorization and other optimizations across the call, which matters in tight loops over tiny functions. Cache effects also matter: a collection of pointers to heap objects of mixed types can have poor locality and mispredicted indirect branches. CRTP helps in hot loops over a single concrete type, but more instantiations increase instruction-cache pressure. The honest answer is to benchmark with realistic data, and to remember that modern compilers can devirtualize when types are visible and with final or LTO.
Recommendation
Use virtual functions when:
- the concrete type is chosen at runtime (plugins, config-driven backends, parsers producing different node types),
- you need heterogeneous containers,
- you expose a stable ABI or want to hide implementation in .cpp files for build time.
Use CRTP (or plain templates and concepts) when:
- the concrete type is known at compile time,
- the code is performance-critical and small functions must inline,
- you want to inject shared behavior (mixins such as comparison operators derived from one function) with zero per-object cost.
Also consider alternatives: std::variant with std::visit for a closed set of types, type erasure for value semantics, and C++20 concepts instead of CRTP when you only need a compile-time constraint.
Common mistakes
- Claiming the vtable layout is mandated by the standard.
- Forgetting the virtual destructor, or not mentioning undefined behavior when deleting through a base.
- Saying virtual calls are "slow" without measurement, or saying CRTP is always faster ignoring code bloat.
- Trying to put
Shape<Circle>andShape<Square>in onevector. - Calling virtual functions from constructors and expecting derived behavior.
- In CRTP, casting to the wrong derived type (
class A : Shape<B>), which is silent undefined behavior; guard with a private constructor andfriend D.
What to ask first
Is the type chosen at runtime? Does the interface cross a shared-library boundary? Are binary size and build time constrained? Then profile the real workload before committing.