skip to content

A C++ class Feet mistakenly derives from Printable<Meters>, and its print() outputs garbage; why does it compile, and how do you make the CRTP base reject it?

level: seniorimportance: should knowfreq 30%

answer

  1. the template trusts its argument
  2. a downcast to the wrong type
  3. undefined behaviour, no diagnostic
  4. who may construct the base

basics

~20 s

Printable<Meters> is a valid base for any class, and static_cast<const Meters&>(*this) is unchecked, so reading a Feet as a Meters is undefined behaviour. Making the base's constructor private and declaring friend Derived turns the slip into a compile error.

solid answer

~40 s

Nothing in `template <class Derived> struct Printable` says that the class inheriting from it must be `Derived`, so `struct Feet : Printable<Meters>` compiles. `print()` then does `static_cast<const Meters&>(*this)` on an object that is really a `Feet`; the standard says the result is defined only if the base subobject is actually part of a `Meters`, so this is undefined behaviour, and in practice it typically reads `Feet`'s bytes as a `Meters`. The fix is to make the base constructible only by `Derived`: declare its default constructor private and write `friend Derived;`. Then `Feet` cannot construct its `Printable<Meters>` base, and the build fails wherever a `Feet` is constructed. A protected destructor adds the second guard: nobody can delete a `Meters` through a `Printable<Meters>*`, which has no virtual destructor.

code

cpp · 16 lines
cpp
#include <iostream>

template <class Derived>
struct Printable {
    void print() const { static_cast<const Derived&>(*this).write(std::cout); }
};
struct Meters : Printable<Meters> {
    double v = 1.5;
    void write(std::ostream& os) const { os << v << " m\n"; }
};
struct Feet : Printable<Meters> {   // copy-paste slip: should be Printable<Feet>
    int v = 7;
    void write(std::ostream& os) const { os << v << " ft\n"; }
};

int main() { Feet f; f.print(); }   // undefined behaviour: Feet is not a Meters

go deeper

for a junior

Recall that the template argument is just a type the base trusts; the language does not check it against the class that derives.

for a middle

Explain why static_cast downcasting a non-Derived object is undefined behaviour and why no exception or check happens.

for a senior

Write the private constructor with friend Derived and the protected destructor, and say which mistake each one blocks and why is_base_of does not.

for a principal

Decide whether guards, a lint rule or C++23 deducing this is the cheaper way to keep a codebase's CRTP bases safe, given its minimum standard.

## The slip and what it does A units library prints values through a CRTP base: - `struct Meters : Printable<Meters>` is correct. - `struct Feet : Printable<Meters>` is a copy-paste slip: the argument should have been `Feet`. The slip compiles cleanly. `Printable<Meters>` is an ordinary class, and any class may derive from it. Nothing in the language ties the template argument to the class doing the deriving; that link is a convention of the pattern, not a rule the compiler knows. At run time `Feet{}.print()` executes `static_cast<const Meters&>(*this)`. The cast itself is well-formed, because `Meters` is a complete class derived from `Printable<Meters>`. But the standard defines the result only when the object really is the base subobject of a `Meters`; otherwise **the behaviour is undefined**. The call to `Meters::write` then reads a `double` where `Feet` stores an `int`. One run with Apple clang 21 printed `3.22967e+209 m`. That number is not the answer to anything: with undefined behaviour any output, a crash or a silently plausible value are all possible. Tools help only partly. UndefinedBehaviorSanitizer's dynamic-type check, `-fsanitize=vptr`, works from the object's vptr, which a non-polymorphic CRTP base does not have. In one run its alignment check happened to report `downcast of misaligned address`, because a `Feet` (holding an `int`) is less strictly aligned than a `Meters` (holding a `double`); a slip between two types with the same alignment would typically pass unreported. ## Guard 1: only Derived may construct the base Make the base's constructor private and befriend the template argument: ```cpp template <class Derived> class Printable { public: void print() const { static_cast<const Derived&>(*this).write(std::cout); } protected: ~Printable() = default; private: Printable() = default; friend Derived; }; ``` `friend Derived;` names a template type parameter as a friend, which C++11 allows. Now: 1. `Meters` constructs its `Printable<Meters>` base, which is legal because `Meters` is the friend. 2. `Feet` tries to construct `Printable<Meters>`, whose constructor is private, and `Feet` is not its friend. 3. The build fails where `Feet` is constructed. Apple clang 21 reports `call to implicitly-deleted default constructor of 'Feet'`, with the note `base class 'Printable<Meters>' has an inaccessible default constructor`. If the base has other constructors, each needs the same treatment; a public constructor left behind reopens the hole. ## Guard 2: no deletion through the base The CRTP base has no virtual destructor, and it should not grow one, since that would add a vptr to every object. Deleting a `Meters` through a `Printable<Meters>*` would therefore be undefined behaviour. A **protected destructor** makes that a compile error: `std::unique_ptr<Printable<Meters>> p(new Meters);` fails with `calling a protected destructor of class 'Printable<Meters>'`, while `Meters` itself can still destroy its base normally. ## Other ways to catch it - A `static_assert(std::is_base_of_v<Printable<Derived>, Derived>)` inside a member function body catches a `Derived` that does not inherit from this base at all, but **not** this slip: `Meters` really does derive from `Printable<Meters>`. The private constructor is the check that matches the actual mistake. - C++23's explicit object parameter (deducing this) removes the argument entirely, so there is nothing to get wrong; it is the alternative to guards when the codebase can require C++23. - Neither that `static_assert` nor a requires-clause can sit on the class template itself. `Meters` is incomplete while `Printable<Meters>` is instantiated as its base, so a check in the class body fails for the **correct** class too: Apple clang 21 reports `incomplete type 'Meters' used in type trait expression`. Checks on `Derived` belong in member function bodies, which are instantiated after `Derived` is complete. - A code review rule or a lint check that the base list repeats the class name is cheap and also effective. ## The senior point The interviewer wants three things: the slip compiles because the language does not know the CRTP convention; the result is undefined behaviour, not a reliable wrong answer; and the base can enforce the convention with access control, a private constructor plus `friend Derived;`, paired with a protected destructor.

  • Why not catch the slip with static_assert(std::is_base_of_v<Printable<Derived>, Derived>)?
    Because the slip passes it. In `struct Feet : Printable<Meters>`, `Derived` is `Meters`, and `Meters` really does derive from `Printable<Meters>`. The assertion catches a `Derived` that never inherits the base, not a second class reusing someone else's argument. The private constructor with `friend Derived;` checks who is constructing the base, which is the actual mistake.
  • Why give a CRTP base a protected destructor instead of a virtual one?
    A virtual destructor would add a vptr to every object and give up the point of the pattern. A protected non-virtual destructor lets derived classes destroy the base normally while making `delete` through a `Base<Derived>*` a compile error, which removes the undefined behaviour that a non-virtual destructor would otherwise allow.

  • The compiler checks that the CRTP argument matches the deriving class.
  • static_cast throws std::bad_cast if the object is not really a Derived.
  • The garbage value is a defined result of reinterpreting the bytes.
  • is_base_of on Derived catches Feet deriving from Printable<Meters>.
  • The fix is to make the CRTP base's destructor virtual.