[Intermediate] — How polymorphism actually works, what a vtable costs, and why modern C++ uses far less inheritance than 1990s C++ did.
Inheritance
class Animal {
protected:
std::string name_;
public:
explicit Animal(std::string n) : name_(std::move(n)) {}
virtual ~Animal() = default; // ESSENTIAL — see below
virtual void speak() const = 0; // pure virtual → abstract class
virtual std::string describe() const { // virtual with a default
return name_ + " is an animal";
}
const std::string &name() const { return name_; } // non-virtual
};
class Dog : public Animal {
public:
explicit Dog(std::string n) : Animal(std::move(n)) {}
void speak() const override { std::cout << name_ << " says woof\n"; }
std::string describe() const override { return name_ + " is a dog"; }
};virtual— this function can be overridden, and calls dispatch on the runtime type= 0— pure virtual. The class is abstract and can’t be instantiatedoverride— always write it; see belowpublicinheritance means “is-a”.privateinheritance means “implemented-in-terms-of” and is rare — prefer composition
Virtual dispatch and the vtable
std::unique_ptr<Animal> a = std::make_unique<Dog>("Rex");
a->speak(); // calls Dog::speak — resolved at RUNTIMEHow: each polymorphic class gets a vtable — a static array of function pointers — and each object gets a hidden vptr pointing at its class’s vtable.
Dog object Dog vtable
┌──────────────┐ ┌──────────────────────┐
│ vptr ─────┼────→│ ~Dog │
│ name_ │ │ Dog::speak │
└──────────────┘ │ Dog::describe │
└──────────────────────┘
A virtual call is: load the vptr, index the vtable, call through the pointer. Two indirections and no inlining — the last part usually costs more than the loads.
This is exactly the struct-of-function-pointers you’d write by hand in C, and exactly what Rust’s `dyn Trait` does. C++ just generates it. Having written one manually in C, the cost model is obvious rather than mysterious.
The costs, concretely:
- +8 bytes per object for the vptr — significant for small, numerous objects
- No inlining through a virtual call unless the compiler can devirtualise
- A cache miss for the vtable lookup, in cold code
final lets the compiler devirtualise when it can prove the type:
class Dog final : public Animal { }; // nobody can derive from Dog
void speak() const final; // nobody can override thisThe virtual destructor rule
class Base { public: ~Base() {} }; // NOT virtual
class Derived : public Base { std::vector<int> data_; };
Base *p = new Derived();
delete p; // UB — only ~Base runs. data_ leaks.If a class has any virtual function, it needs a virtual destructor. If it’s meant to be a base class, it needs a virtual destructor.
virtual ~Base() = default;The alternative, for a base class not meant to be deleted polymorphically, is a protected non-virtual destructor — which makes delete p through a Base* a compile error instead of UB.
override and final
class Dog : public Animal {
void speak() override; // compiler CHECKS this overrides something
};Without override, a signature mismatch silently creates a new function instead of overriding:
class Animal { virtual void speak() const; };
class Dog : public Animal {
void speak(); // missing const → NEW function, not an override
// Animal::speak still called through a base ptr
};That bug is silent, common, and produces “my override isn’t being called”. Always write override. Turn on -Wsuggest-override.
Object slicing
The trap that has no equivalent in reference-based languages:
void process(Animal a); // BY VALUE — takes an Animal
Dog d("Rex");
process(d); // SLICED — only the Animal part is copied
// virtual dispatch is lost; a.speak() calls Animal::speakCopying a Dog into an Animal-sized slot literally discards everything the derived class added. It compiles without a warning.
Polymorphism requires a pointer or a reference.
Animal&,Animal*,unique_ptr<Animal>— neverAnimalby value.
Making the base class abstract (any pure virtual) prevents slicing, because you then can’t have an Animal by value at all. That’s a good reason to have at least one pure virtual in an interface.
Multiple inheritance and the diamond
C++ allows multiple inheritance, which produces the diamond problem:
class A { public: int x; };
class B : public A {};
class C : public A {};
class D : public B, public C {}; // D has TWO copies of A::x
D d;
d.x; // ambiguous — B::x or C::x?
d.B::x; // must qualifyclass B : virtual public A {}; // virtual inheritance — ONE shared A
class C : virtual public A {};
class D : public B, public C {}; // d.x is now unambiguousVirtual inheritance adds runtime cost and complicates construction (the most-derived class initialises the virtual base). Later languages banned this entirely — Java allows multiple interface inheritance only, Rust has traits with no data.
The practical rule: inherit from at most one class with data, and any number of pure-interface classes.
class Drawable { public: virtual ~Drawable() = default; virtual void draw() const = 0; };
class Serialisable { public: virtual ~Serialisable() = default; virtual std::string to_json() const = 0; };
class Widget : public Drawable, public Serialisable { }; // fine — no data, no diamondWhy modern C++ uses less inheritance
1990s C++ taught deep hierarchies. Current practice doesn’t, for reasons that hold across languages:
- Fragile base class — changing a base breaks derived classes in ways you can’t see from the base
- Tight coupling — inheritance is the strongest coupling available
- It forces runtime dispatch where compile-time would do
- Slicing — a whole bug class that composition doesn’t have
The alternatives, in rough order of preference:
Composition — hold the thing rather than being it:
class Car {
Engine engine_; // has-a, not is-a
std::vector<Wheel> wheels_;
};Templates for static polymorphism — no vtable, fully inlinable:
template <typename Shape>
double total_area(const std::vector<Shape> &shapes) {
double t = 0;
for (const auto &s : shapes) t += s.area(); // resolved at COMPILE time
return t;
}Type erasure — std::function is the everyday example, letting you store any callable without a hierarchy:
std::vector<std::function<void()>> callbacks;std::variant + std::visit — a closed set of types, checked exhaustively:
using Shape = std::variant<Circle, Square, Triangle>;
double area(const Shape &s) {
return std::visit([](const auto &x) { return x.area(); }, s);
}This is the sum type approach, and it’s better than inheritance when the set of types is closed and known. Inheritance is better when it’s open — plugins, user-extensible types.
The rule of thumb: use inheritance for open sets of types that share behaviour and need runtime dispatch. Use
variantfor closed sets. Use templates when the type is known at compile time. Use composition for everything else.
RTTI
Animal *a = get_animal();
if (Dog *d = dynamic_cast<Dog *>(a)) { } // null if it isn't a Dog
Dog &d = dynamic_cast<Dog &>(*a); // THROWS std::bad_cast if not
std::cout << typeid(*a).name(); // implementation-defined stringdynamic_cast is checked at runtime and requires RTTI to be enabled. It’s relatively slow, and frequent dynamic_cast is a design smell — it usually means a virtual function is missing, or variant was the right model.
Many projects (games, embedded) compile with -fno-rtti to save binary size, which disables dynamic_cast and typeid entirely.
Practical rules
virtual ~Base() = defaulton any polymorphic base.overrideon every override.finalwhere it helps.- Never pass polymorphic types by value — slicing.
- At most one data-carrying base, any number of pure interfaces.
- Prefer composition. Inheritance is the strongest coupling you can create.
variantfor closed sets, inheritance for open ones.- Frequent
dynamic_castmeans the design is wrong.
Related
- Templates and Concepts — static polymorphism
- The STL Containers —
std::variantand friends - Rust: Traits — no inheritance at all
- C: Function Pointers — the vtable, by hand
- Design Patterns — most of which are about avoiding this
- C++ course map
Software engineering
Infrastructure & security
Computer science
Hardware & engineering