Skip to content
LeetQuant
QD03 C++ Fundamentals

QD03 · C++ Fundamentals · Lesson 6 of 6

Classes and Polymorphism

Encapsulation and invariants, inheritance, virtual functions and how vtables implement them, virtual destructors, object slicing, and when to replace virtual dispatch with templates or std::variant.

18 min

Encapsulation protects invariants

The objective is to use inheritance and virtual functions correctly, to explain what a virtual call costs, and to know the alternatives a low-latency codebase prefers.

A class bundles data with the functions that keep it consistent. Make data private when the class has an invariant, a condition that must always hold, such as "a price level's quantity is positive" or "the best bid is below the best ask". Public member functions then become the only way to change state, and each can check the invariant. A struct with public members is fine for plain data with no invariant (a Quote or a Fill); struct and class differ only in their default access (public versus private).

Other basics that come up: mark single-argument constructors explicit so an int does not silently convert into your type; use protected for members derived classes may touch; and prefer composition (a class has a member) over inheritance unless you need the base type's interface (a class is a kind of the base).

Virtual functions and runtime polymorphism

Inheritance lets code written against a base class work with any derived class. Declaring a member function virtual makes calls through a base pointer or reference dispatch on the object's dynamic (actual) type rather than the static type of the pointer. A pure virtual function (= 0) has no implementation in the base, which makes the base abstract: it cannot be instantiated, only derived from. Mark overrides with override so the compiler rejects a signature that does not actually override (a missing const silently creates a new function otherwise), and final to forbid further overriding.

#include <iostream>
#include <memory>
#include <vector>

class Instrument {
public:
    explicit Instrument(double px) : px_(px) {}
    virtual ~Instrument() = default;           // deleting through a base pointer is safe
    virtual double delta() const = 0;          // pure virtual: Instrument is abstract
    virtual const char* name() const { return "instrument"; }
    double price() const { return px_; }       // non-virtual: same for all

protected:
    double px_;
};

class Stock : public Instrument {
public:
    using Instrument::Instrument;
    double delta() const override { return 1.0; }
    const char* name() const override { return "stock"; }
};

class Call : public Instrument {
public:
    Call(double px, double d) : Instrument(px), d_(d) {}
    double delta() const override { return d_; }
    const char* name() const override { return "call"; }

private:
    double d_;
};

int main() {
    std::vector<std::unique_ptr<Instrument>> book;
    book.push_back(std::make_unique<Stock>(250.0));
    book.push_back(std::make_unique<Call>(12.5, 0.55));
    double portfolio_delta = 0.0;
    for (const auto& inst : book) {
        std::cout << inst->name() << " price " << inst->price() << " delta " << inst->delta() << '\n';
        portfolio_delta += inst->delta();
    }
    std::cout << "total delta " << portfolio_delta << '\n';

    struct Plain { double x; };
    struct WithVirtual { double x; virtual ~WithVirtual() = default; };
    std::cout << "sizeof Plain " << sizeof(Plain) << ", sizeof WithVirtual " << sizeof(WithVirtual) << '\n';
}
stock price 250 delta 1
call price 12.5 delta 0.55
total delta 1.55
sizeof Plain 8, sizeof WithVirtual 16

(std::unique_ptr owns each heap-allocated object and deletes it through the base pointer; QD04 covers it. A container of polymorphic objects must hold pointers, for the slicing reason below.)

How it works. Each class with virtual functions has one static vtable: an array of function pointers, one slot per virtual function. Each object of such a class carries a hidden vptr pointing at its class's vtable, set by the constructor. A virtual call inst->delta() loads the vptr from the object, loads the function pointer from the slot, and makes an indirect call. That vptr is why WithVirtual is 16 bytes on a 64-bit machine: 8 for the double, 8 for the vptr. (The standard does not mandate vtables, but every mainstream compiler uses them.)

While a base constructor or destructor runs, the object's dynamic type is the base, so a virtual call from inside Instrument's constructor calls Instrument's version (or is undefined behaviour if it is pure virtual), never the derived override.

Virtual destructors and slicing

Virtual destructors. If you delete a derived object through a base pointer and the base destructor is not virtual, the behaviour is undefined; in practice only the base destructor runs and the derived part's resources leak:

#include <iostream>

struct Base {
    ~Base() { std::cout << "~Base\n"; }  // NOT virtual
};
struct Feed : Base {
    ~Feed() { std::cout << "~Feed (closes socket)\n"; }
};

int main() {
    Base* p = new Feed;
    delete p;  // undefined behaviour
}

This build printed only ~Base; the socket would never be closed. Rule: a class meant to be used polymorphically (any class with a virtual function) needs a public virtual destructor, or a protected non-virtual one so that deleting through the base does not compile.

Slicing. Copying a derived object into a base object (not a reference or pointer) copies only the base sub-object. The derived members and the derived behaviour are cut off, because the copy really is a Base, with Base's vptr:

#include <iostream>

struct Base {
    virtual const char* who() const { return "Base"; }
    virtual ~Base() = default;
};
struct Derived : Base {
    int extra = 42;
    const char* who() const override { return "Derived"; }
};

void by_value(Base b) { std::cout << "by value:     " << b.who() << '\n'; }
void by_ref(const Base& b) { std::cout << "by reference: " << b.who() << '\n'; }

int main() {
    Derived d;
    by_value(d);  // copies only the Base part: slicing
    by_ref(d);    // no copy: dynamic type is still Derived
    Base copy = d;
    std::cout << "copy:         " << copy.who() << '\n';
}
by value:     Base
by reference: Derived
copy:         Base

This is why polymorphic objects are passed by reference or pointer, stored in containers as pointers (std::vector<Base> slices every element), and why polymorphic base classes often delete their copy operations.

What a virtual call costs, and the alternatives

A virtual call costs two dependent loads and an indirect branch, a few nanoseconds at most when everything is cached and the branch predictor guesses the target. The larger costs are indirect:

  • The compiler usually cannot inline a virtual call, so it loses every optimisation that inlining enables (constant folding, vectorising the loop around the call). Compilers sometimes devirtualise when they can prove the dynamic type, for example when the class is final.
  • A loop over objects of mixed types makes the indirect branch harder to predict, and the vtable and code for each type compete for cache.
  • Polymorphic objects usually live behind pointers on the heap, so iterating them chases pointers instead of streaming contiguous memory.

None of this matters for code that runs once per order or per configuration change; it matters in an inner loop over millions of ticks. Two alternatives move the dispatch to compile time:

ApproachDispatchSet of typesStorageGood for
virtual functionsruntime, through the vtableopen: new types can be added in other code (plugins)usually behind pointersflexible interfaces, many types, code that is not hot
templates (static polymorphism)compile time; calls can inlinefixed per instantiationby valuea hot path where the type is known at compile time, e.g. a strategy plugged into a backtest loop
std::variant + std::visita switch on a stored indexclosed: listed in the variantby value, contiguous in a vectora known, small set of message or instrument types

A template version of "strategy" needs no base class at all; any type with the right member function works, and each run<Momentum> is compiled and inlined separately:

#include <iostream>

// Static polymorphism: the strategy type is a template parameter, so the call to
// signal is resolved at compile time and can be inlined.
struct Momentum {
    int signal(double ret) const { return ret > 0 ? 1 : (ret < 0 ? -1 : 0); }
};
struct Reversion {
    int signal(double ret) const { return ret > 0 ? -1 : (ret < 0 ? 1 : 0); }
};

template <typename Strategy>
int run(const Strategy& s, const double* rets, int n) {
    int pos = 0;
    for (int i = 0; i < n; ++i) pos += s.signal(rets[i]);
    return pos;
}

int main() {
    double rets[] = {0.01, -0.02, 0.005, 0.0, 0.03};
    std::cout << run(Momentum{}, rets, 5) << ' ' << run(Reversion{}, rets, 5) << '\n';  // prints: 2 -2
}

Three positive returns, one negative and one zero give momentum 3−1=23 - 1 = 2 and reversion −2-2. The cost of this approach: the strategy cannot be chosen at runtime from a config file without some dispatch somewhere, and every strategy adds a copy of run to the binary.

Worked example

replace an instrument hierarchy with std::variant

A risk loop sums the delta of a book of stocks (delta 1), calls (delta stored per option) and futures (delta 1 per contract). The set of instrument types is fixed. Rewrite the virtual-function design with std::variant so the book is a contiguous std::vector of values, and compute the total delta of one stock, one call with delta 0.55 and one future.

Show solution

A std::variant<Stock, Call, Future> holds exactly one of the three types in place, plus a small index saying which. Its size is the largest alternative plus the index, rounded up for alignment, and it needs no heap allocation, so a std::vector<Instrument> stores the instruments contiguously. std::visit calls a visitor with the active alternative; a generic lambda with if constexpr handles each type, and the compiler builds the dispatch as a jump table or a chain of comparisons, with each branch inlinable.

#include <iostream>
#include <type_traits>
#include <variant>
#include <vector>

struct Stock { double px; };
struct Call  { double px; double delta; };
struct Future { double px; double multiplier; };

using Instrument = std::variant<Stock, Call, Future>;

double delta_of(const Instrument& inst) {
    return std::visit([](const auto& x) -> double {
        using T = std::decay_t<decltype(x)>;
        if constexpr (std::is_same_v<T, Stock>) return 1.0;
        else if constexpr (std::is_same_v<T, Call>) return x.delta;
        else return 1.0;  // Future: delta one per contract
    }, inst);
}

int main() {
    std::vector<Instrument> book{Stock{250.0}, Call{12.5, 0.55}, Future{5000.0, 50.0}};
    double total = 0.0;
    for (const auto& inst : book) total += delta_of(inst);
    std::cout << "total delta " << total << ", sizeof(Instrument) " << sizeof(Instrument) << '\n';
}
total delta 2.55, sizeof(Instrument) 24

Check: 1+0.55+1=2.551 + 0.55 + 1 = 2.55. The largest alternatives (Call, Future) are 16 bytes; the index adds padding up to the 8-byte alignment, giving 24 on this platform.

The trade-off to state in an interview. Adding a new operation (say vega_of) is easy: write another visitor, no class changes. Adding a new type means editing the variant and every visitor; with if constexpr and a final else a forgotten type silently takes the default branch, so many teams use an overload set of lambdas instead, which fails to compile when a type is not handled. Virtual functions have the opposite trade-off: new types are easy, new operations touch every class. Choose variant for a closed set of types on a hot path, and virtual functions for open extension.

Knowledge check

Derived overrides the virtual function who() from Base. void f(Base b) { print(b.who()); } is called as f(derived_object). What is printed, and why?

Knowledge check

On a typical 64-bit compiler, struct P { double x; }; is 8 bytes. What is sizeof(Q) for struct Q { double x; virtual void f(); };?

Knowledge check

Base has a non-virtual public destructor and a virtual member function. Code does Base* p = new Derived; delete p; where Derived owns a socket. What does the standard say?

Knowledge check

In a hot loop over millions of market-data messages of five fixed types, what is usually the main cost of handling them through virtual functions, compared with std::variant?

Key takeaways

  • Make data private when the class has an invariant; prefer composition to inheritance.
  • Virtual functions dispatch on the dynamic type through a per-class vtable and a per-object vptr (8 bytes per object on 64-bit). Use override, and do not rely on virtual calls from constructors or destructors.
  • Any class used polymorphically needs a virtual destructor (or a protected non-virtual one).
  • Copying a derived object into a base object slices it; pass and store polymorphic objects by reference or pointer.
  • Virtual calls cost an indirect branch and lost inlining. For hot paths, use templates when the type is known at compile time and std::variant for a closed set of types; keep virtual functions for open, non-hot interfaces.

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).