skip to content

Virtual Functions

A virtual call dispatches on the object's dynamic type, a missing virtual destructor leaks, and copying a derived object into a base slices it. Interviewers ask all three.

on this pageshow

explore

questions

6

In C++, what do the override and final specifiers do on a virtual member function, and which bug does override catch?

level: juniorimportance: must knowfreq 72%

answer

  1. a promise the compiler checks
  2. signature drift: const, parameter types
  3. silent hiding instead of overriding
  4. final on a function and on a class

basics

~20 s

Since C++11, override asks the compiler to prove that a member function overrides a base virtual; if it does not, the program is ill-formed. final forbids further overriding of a function, or any derivation from a class.

solid answer

~40 s

`override` is a promise the compiler checks: a function marked with it that does not override a base virtual function makes the program **ill-formed**. That catches the classic silent bug where a derived function differs by a parameter type (`int` instead of `std::size_t`) or a missing `const`, or where someone later changes the base signature: without `override` the derived function is simply a new, non-virtual function that **hides** the base one, and calls through `Effect&` still run the base version. `final` on a virtual function forbids any further override, and `final` on a class (`struct Reverb final : Effect`) forbids deriving from it. Both arrived in C++11 as identifiers with special meaning, not reserved keywords. House style is to write exactly one of `virtual`, `override` or `final` on each declaration.

code

cpp · 18 lines
cpp
#include <cstdio>

struct Effect {
    virtual ~Effect() = default;
    virtual const char* name() const { return "effect"; }
};

struct Delay : Effect {
    const char* name() { return "delay"; }  // no const: a new function, not an override
};

void show(const Effect& e) { std::puts(e.name()); }

int main() {
    Delay d;
    show(d);               // prints "effect"
    std::puts(d.name());   // prints "delay"
}

go deeper

for a junior

Know that override makes the compiler verify the function really overrides, final stops further overriding or derivation, and both came in C++11.

for a middle

Explain how a signature mismatch silently hides instead of overriding, why the bug only shows through a base reference, and how override turns it into an error.

for a senior

Bring in what override does not catch: default arguments bound by static type, covariant return limits, and enabling -Wsuggest-override so the whole codebase uses the specifier.

for a principal

Treat it as a codebase convention: exactly one of virtual, override or final per declaration, leaf classes final by default, and warnings that enforce both in CI.

## How a function becomes an override In C++ a member function overrides a base class virtual function when it has the **same name, the same parameter list and the same cv-qualification** as the base declaration; a differing ref-qualifier is not a way out, since the standard requires an overrider's ref-qualifier to match. The `virtual` keyword on the derived declaration is optional: the standard calls it valid but redundant. That flexibility is the trap. If any part of the signature differs, the derived function does not override anything. It is a brand-new function that **hides** the base function of the same name in the derived class's scope, and the language does not treat that as an error. ```cpp struct Effect { virtual ~Effect() = default; virtual void process(float* buf, std::size_t n); virtual const char* name() const; }; struct Delay : Effect { void process(float* buf, int n); // different parameter type: hides const char* name(); // missing const: hides }; ``` Through a `Delay` object you call `Delay`'s functions, so the code looks fine in a quick test. Through the `Effect&` the audio graph actually uses, both calls go to `Effect`'s versions. Typical sources of this bug: - a parameter type that is close but different: `int` versus `std::size_t`, `float` versus `double`, `T&` versus `const T&`; - a missing or extra `const` on the member function; - a base class signature changed in a refactor while some derived classes were not updated; - a misspelt name, which produces a separate function rather than an error. ## override: make the compiler check it ```cpp struct Delay : Effect { void process(float* buf, int n) override; // error const char* name() override; // error }; ``` The standard says that a function marked `override` which does not override a member function of a base class makes the program **ill-formed**, so every case in the list above becomes a compile error. Apple clang 21 reports it as `error: non-virtual member function marked 'override' hides virtual member function`. Clang's `-Wall` also includes `-Woverloaded-virtual`, which warns about the missing-`const` hiding even without `override`, and both GCC and Clang offer `-Wsuggest-override` to flag overriding functions that lack the specifier. ## final: close a function or a class `final` has two uses: | Where | Meaning | Error if violated | |---|---|---| | on a virtual function: `void process(float*, std::size_t) final;` | no class further down may override it | a derived declaration that would override it is ill-formed | | on a class: `struct Reverb final : Effect` | no class may derive from it | naming it as a base class is ill-formed | `final` does not stop dynamic dispatch through a base reference: `Effect& e = reverb; e.process(...)` still calls `Reverb::process`. What it adds is knowledge. When the compiler sees a call through a `Reverb&` and `Reverb` is final, it knows the exact function and may call it directly; how much that buys is a question of dispatch cost, covered with vtables. ## Spelling and history 1. `override` and `final` arrived in **C++11**. They are **identifiers with special meaning**, not reserved keywords, so older code with a variable named `final` still compiles; they act as specifiers only in their declarator position. 2. Write **exactly one** of `virtual`, `override` or `final` per declaration: `virtual` to introduce a new virtual function, `override` on an overrider, `final` on an overrider that ends the chain. `virtual void f() override` is legal but noisy. 3. A destructor can be marked `override` too, which documents that the base destructor is virtual. 4. An overrider may return a **covariant** type: if the base returns `Effect*`, the override may return `Reverb*`, since both are pointers to classes and `Effect` is an accessible base of `Reverb`. Smart pointers are not covariant: a `std::unique_ptr<Reverb>` return does not override a `std::unique_ptr<Effect>` one. ## What override does not check - **Default arguments.** A virtual call uses the default arguments of the declaration found through the **static type**; an overrider does not inherit them. If `Effect::process(float*, std::size_t n = 64)` and `Delay` declares `n = 128`, calling through `Effect&` passes 64 to `Delay::process`. Never redeclare different defaults on an override. - **Access.** Overriding ignores access control, so a `private` override still runs when called through a `public` base function. - **Intent at the base.** `override` checks the derived side; nothing forces the base author to make the right functions virtual in the first place.

  • If Effect::process declares a default argument n = 64 and Delay's override declares n = 128, what does a call through Effect& pass?
    It passes 64. Default arguments are bound from the declaration found through the static type, while the function body is chosen from the dynamic type, so `Delay::process` runs with `Effect`'s default. An overrider never inherits or replaces the base's defaults; keep defaults on the base only, or avoid them on virtual functions.
  • Can an override return a different type from the base function?
    Only a covariant one: if the base returns a pointer or reference to a class, the override may return a pointer or reference to a class derived from it, such as `Reverb*` for `Effect*`. Any other difference in return type alone is ill-formed. `std::unique_ptr<Reverb>` is not covariant with `std::unique_ptr<Effect>`, so a clone function returning smart pointers keeps the base return type.

  • Writing override makes a function virtual even if the base has no matching one.
  • Marking a class final stops virtual calls through a base reference from reaching it.
  • A missing const just creates an overload, and virtual calls still pick the derived one.
  • override and final are reserved keywords, so nothing may be named final.
  • Overriders inherit the base function's default arguments.
open as a page

In C++, what goes wrong when you delete a derived Reverb object through an Effect* whose destructor is not virtual?

level: juniorimportance: must knowfreq 82%

basics

~20 s

The delete has undefined behaviour. In practice compilers usually call only ~Effect, so ~Reverb and the destructors of Reverb's members never run and whatever they own leaks. Declaring virtual ~Effect() = default in the base fixes it.

open as a page

In C++, what happens when a Reverb object is stored in a std::vector<Effect> or passed to a function taking Effect by value?

level: middleimportance: must knowfreq 70%

basics

~10 s

The Reverb is sliced: Effect's copy constructor builds a brand-new Effect from the Effect part of the Reverb, so Reverb's data is lost and virtual calls on the copy run Effect's functions, not Reverb's.

open as a page

In C++, what makes a class abstract, can a pure virtual function have a definition, and why must a pure virtual destructor be defined?

level: middleimportance: should knowfreq 55%

basics

~20 s

A class is abstract while some pure virtual function, declared with = 0, is still its final overrider. A pure virtual may have a body, reached by qualified call, and a pure virtual destructor must be defined because derived destructors call it.

open as a page

In C++, an Effect constructor calls the virtual reset() that Delay overrides; which reset() runs, and what changes if reset() is pure virtual?

level: seniorimportance: should knowfreq 60%

basics

~10 s

Effect::reset runs, not Delay::reset: during Effect's constructor and destructor a virtual call resolves to the final overrider in Effect itself. If that function is pure, the call is undefined behaviour, often an abort.

open as a page

In a C++ audio plugin framework whose virtual Effect::process() runs per sample, how do you decide between keeping it virtual and moving to std::variant or templates?

level: principalimportance: should knowfreq 40%

basics

~20 s

Decide by who extends the set and where the cost really is. Third-party effects loaded at run time need a virtual interface; a closed built-in set can be a std::variant; a fixed chain can be templates. Often process() per block fixes it.

open as a page