KatInterview

Runtime Polymorphism vs Static Polymorphism in C++

System DesignModel answer
MediumModel answerSystem Designcppvirtual-functionscrtp

Last 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:

  1. 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.
  2. Explain the Curiously Recurring Template Pattern (CRTP) and how it provides polymorphism without virtual calls.
  3. 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.
  4. 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?