In C++, what does a CRTP base give up compared with an abstract base class with virtual functions?
answer
- no common base type
- every user becomes a template
- one copy per derived type
- no vptr in the object
basics
~20 sA CRTP base gives up a common base type: Drawable<Mesh> and Drawable<Sprite> are unrelated, so one container or pointer cannot hold both. Generic code over them must be a template, built once per type, in exchange for no vptr and inlinable calls.
solid answer
~40 sWith virtual functions every derived class shares one base, so `std::vector<std::unique_ptr<Drawable>>` holds any mix and a function taking `const Drawable&` is compiled once. With CRTP each derived class has a different base, `Drawable<Mesh>` versus `Drawable<Sprite>`, so there is no single pointer type: a function that accepts them must itself be a template, `template <class D> void draw_twice(const Drawable<D>&)`, defined in a header and generated once per type. Mixing types in one container needs a closed set, such as a `std::variant<Mesh, Sprite>` with `std::visit`, or a virtual interface after all. What you gain is that calls are bound at compile time and can be inlined, and objects carry no vptr. Errors also move to compile time, but surface as template instantiation errors.
code
cpp · 24 lines#include <iostream>
#include <variant>
#include <vector>
template <class Derived>
struct Drawable {
void draw() const { static_cast<const Derived&>(*this).draw_impl(); }
};
struct Mesh : Drawable<Mesh> { void draw_impl() const { std::cout << "mesh\n"; } };
struct Sprite : Drawable<Sprite> { void draw_impl() const { std::cout << "sprite\n"; } };
// Drawable<Mesh> and Drawable<Sprite> share no base, so there is no
// std::vector<Drawable*>; a closed set of types goes in a variant instead.
using AnyDrawable = std::variant<Mesh, Sprite>;
template <class D>
void draw_twice(const Drawable<D>& d) { d.draw(); d.draw(); } // one copy per D
int main() {
std::vector<AnyDrawable> scene{Mesh{}, Sprite{}};
for (const auto& item : scene)
std::visit([](const auto& d) { d.draw(); }, item);
draw_twice(Mesh{});
}go deeper
Recall that CRTP calls are resolved at compile time and that Drawable<Mesh> and Drawable<Sprite> are different classes.
Explain the structural cost: no common base pointer, every generic consumer is a template, and a mixed container needs a closed set such as std::variant.
Show the layering used in real code: a virtual interface at the module boundary, CRTP helpers implementing it once, and static calls inside hot code.
Decide by whether the set of types is open or closed and who adds types: an open set across library boundaries needs virtual dispatch whatever CRTP would save.
## Two ways to write one interface for many types C++ offers two mechanisms for "the base calls code that each derived class supplies": - **Dynamic polymorphism**: an abstract base `IDrawable` with a `virtual void draw() const = 0;` that each class overrides. The call is resolved at run time through the object's vtable. - **Static polymorphism with CRTP**: a template `Drawable<Derived>` whose `draw()` does `static_cast<const Derived&>(*this).draw_impl()`. The call is resolved when the compiler instantiates `Drawable<Mesh>::draw`. The interview question is what the second one costs, and the answer is mostly about **types**, not speed. ## What CRTP gives up 1. **A common base type.** `Drawable<Mesh>` and `Drawable<Sprite>` are two unrelated classes. There is no `Drawable*` that can point at either, no `std::vector<std::unique_ptr<Drawable>>` scene list, and no single base type for an object whose class is chosen at run time; a closed `std::variant` has to be built for that. 2. **Non-template consumers.** A function that should accept "any drawable" must be a template, `template <class D> void draw_twice(const Drawable<D>& d)`. Templates generally live in headers, and the requirement spreads: whatever calls `draw_twice` generically is a template too. 3. **One body for all types.** Each derived class instantiates its own copy of every base member and every generic consumer it is used with. With many types and large functions the binary and the build both grow; how much depends on inlining and on whether the linker folds identical functions. 4. **Plugin boundaries.** A shared library loaded at run time can hand you an object behind a virtual interface; it cannot hand you a type the caller's templates were never instantiated for. 5. **Readable errors.** A missing `draw_impl` is caught at compile time, which is good, but it is reported from inside the base template's instantiation rather than as "does not override a pure virtual function". ## What it gains | | Virtual functions | CRTP | |---|---|---| | Call binding | run time, through the vtable | compile time, per instantiation | | Inlining across the call | only if the compiler can devirtualize | ordinary inlining | | Per-object overhead | a vptr (8 bytes on common 64-bit ABIs) | none | | Mixing types in one container | yes, through base pointers | only through a closed set such as `std::variant` | | Adding a type later, without recompiling users | yes | no | On Apple clang 21 a class holding one `double` is 8 bytes as a CRTP type and 16 bytes once it has a virtual function, because of the vptr. That size is an implementation's layout choice, not something the standard specifies. ## Recovering heterogeneity when you need it When the set of types is closed and known, `std::variant<Mesh, Sprite>` stores either by value in one container, and `std::visit` with a generic lambda calls the right `draw()` for each, still without virtual functions. When the set is open (plugins, user-defined types added later), the honest answer is a virtual interface, possibly implemented on top of CRTP helpers: a CRTP class can derive from an abstract base and implement its virtual functions once for every type. Many codebases use exactly that layering: virtual at the boundary, static inside. ## A short decision list - **Closed set, types known at compile time, calls in hot code**: CRTP, or a `std::variant` of the types when they must share a container. - **Open set, types chosen from data or loaded from plugins**: an abstract base with virtual functions. - **Both at once**: virtual functions at the module boundary, CRTP helpers implementing them once, static calls inside each class. - **Only shared helper functions, C++23 available**: an explicit object parameter on a plain base, which needs no template argument at all. ## How to answer Lead with the structural cost, which candidates often miss: CRTP is not a drop-in replacement for an interface, because it has no common base type and turns every consumer into a template. Then give what it buys: compile-time binding, inlining, no vptr. A strong answer names the closed-set escape hatch (`std::variant`) and says when the set of types must stay open, which means virtual functions. How the vtable call itself performs in a hot loop is a separate question about inlining and dispatch cost.
- Can one class use CRTP and still be stored behind a virtual interface?Yes. A CRTP helper can itself derive from an abstract base: `template <class D> struct DrawableImpl : IDrawable { void draw() const override { static_cast<const D&>(*this).draw_impl(); } };`. Each class derives from `DrawableImpl<ItsName>`, gets the override written once, and can be held as `IDrawable*`. The boundary pays for virtual dispatch; code inside each class keeps static calls.
- Why does a function taking any CRTP type have to live in a header?It must be a template, `template <class D> void f(const Drawable<D>&)`, because there is no single parameter type. A template is instantiated in the translation unit that calls it, so its definition has to be visible there, which in practice means a header, unless you explicitly instantiate it for a known list of types.
- A std::vector<Drawable*> can hold both CRTP Mesh and Sprite objects.
- CRTP and virtual functions are interchangeable; CRTP is just faster.
- CRTP objects still carry a vptr, only the call is cheaper.
- A new CRTP type can be loaded from a plugin without recompiling users.
- Choosing CRTP means you can never use std::visit or containers of mixed types.