# Inheritance and Virtual Functions

> How C++ lays out base subobjects, dispatches virtual calls through vtables, handles multiple and virtual inheritance, and traps callers during construction and destruction.

- **Source:** C++ Atlas (https://cppatlas.com/topics/inheritance-and-virtual-functions)
- **Track:** Classes
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [class.derived] (https://eel.is/c++draft/class.derived), [class.mi] (https://eel.is/c++draft/class.mi), [class.virtual] (https://eel.is/c++draft/class.virtual), [class.abstract] (https://eel.is/c++draft/class.abstract), [class.dtor] (https://eel.is/c++draft/class.dtor), [class.cdtor] (https://eel.is/c++draft/class.cdtor), [class.access.virt] (https://eel.is/c++draft/class.access.virt), [expr.dynamic.cast] (https://eel.is/c++draft/expr.dynamic.cast)
- **cppreference links:** [Derived classes](https://en.cppreference.com/w/cpp/language/derived_class), [virtual function specifier](https://en.cppreference.com/w/cpp/language/virtual), [override specifier](https://en.cppreference.com/w/cpp/language/override), [final specifier](https://en.cppreference.com/w/cpp/language/final), [Abstract class](https://en.cppreference.com/w/cpp/language/abstract_class), [Destructors](https://en.cppreference.com/w/cpp/language/destructor), [dynamic_cast conversion](https://en.cppreference.com/w/cpp/language/dynamic_cast), [Using-declaration](https://en.cppreference.com/w/cpp/language/using_declaration)
- **Prerequisites:** constructors-and-initialization-order, casts-and-qualifiers

Inheritance in C++ serves two distinct purposes: composing object representations by embedding base subobjects, and dispatching behavior dynamically through interfaces. Confusing those two mechanisms—especially how memory layout interacts with compile-time lookup versus runtime dispatch—causes slicing, undefined deletion, and surprising access bugs.

## Base subobjects and object layout

When `Derived` inherits from `Base`, C++ does not allocate `Base` separately and store a hidden heap pointer. Instead, the `Base` subobject lives directly inside the byte footprint of `Derived` (`[class.derived]`). Under single non-virtual inheritance on common ABIs, the base subobject typically starts at offset zero, followed by `Derived`'s own data members.

> **Mental model.** A `Derived` object is a single contiguous block containing one or more embedded `Base` subobjects plus `Derived`'s own members. Passing `Derived` by value to a parameter of type `Base` copies only the `Base` slice and leaves a plain `Base` object behind.

That embedded layout explains **object slicing**. If a function takes `Base b` by value and receives a `Derived`, copy construction initializes `b` strictly from `Derived`'s `Base` subobject; any derived state vanishes, and `b`'s dynamic type becomes `Base`. Polymorphic callers must therefore pass references (`Base&`, `const Base&`) or pointers (`Base*`, `std::unique_ptr<Base>`).

If a base class has no non-static data members and no virtual functions, the **empty base optimization** (EBO) lets the compiler give that base subobject zero size inside `Derived` (provided two bases of the same type do not share an address). Under multiple inheritance (`struct C : A, B`), `C` embeds both `A` and `B` sequentially. Converting a non-null `C*` to `B*` shifts the pointer address forward by `B`'s offset inside `C`, whereas converting a null `C*` preserves `nullptr`.

## Dynamic dispatch, vtables, and override safety

Every expression of class, pointer, or reference type has a **static type** fixed at compile time and—for polymorphic classes declaring or inheriting at least one `virtual` function—a **dynamic type** belonging to the most-derived object currently occupying that storage.

Compilers almost universally implement `virtual` dispatch with two structures: one read-only **vtable** (virtual function table) per polymorphic class holding function pointers and RTTI metadata, and one hidden **vptr** pointer embedded inside each polymorphic object instance pointing to its dynamic class's vtable. Calling `base_ptr->encode(42)` loads the vptr from `*base_ptr`, indexes into the slot assigned to `encode`, and calls the target address.

```cpp
struct Codec {
    virtual ~Codec() = default;
    virtual int encode(int x) const = 0; // pure virtual makes Codec abstract
};

int Codec::encode(int x) const { return x; } // legal out-of-class fallback definition

struct FastCodec final : Codec {
    int encode(int x) const override {
        return x * 2 + Codec::encode(1); // qualified call bypasses vtable dispatch
    }
};
```

Always mark overriding functions `override`. Without `override`, changing a parameter type, omitting `const`, or dropping a `&`/`&&` ref-qualifier silently creates a brand-new unrelated virtual or non-virtual function instead of overriding the base slot. Adding `final` on a class or virtual member seals further overriding and enables the optimizer to devirtualize calls through pointers of that static type. Notice also that a pure virtual function (`= 0`) prevents direct instantiation of `Codec` (`[class.abstract]`), yet may still provide a definition invoked explicitly via qualified syntax (`Codec::encode(1)`).

## Name hiding, using-declarations, and access traps

C++ splits name lookup, access checking, and default arguments from virtual dispatch. Neglecting that split produces two classic surprises.

First, **name hiding** happens during unqualified lookup before overload resolution begins. If `Derived` declares `void log(double)`, that declaration hides *every* overload named `log` in `Base`, including `void log(int)`. Calling `derived.log(42)` silently picks `log(double)` unless `Derived` pulls base overloads into scope with `using Base::log;`.

Second, **access control** (`public`, `protected`, `private`) and **default arguments** on a virtual call are resolved strictly against the **static type** of the call expression (`[class.access.virt]`), while the function body itself is chosen by the **dynamic type**.

```cpp
struct Base {
    virtual void log(int x = 10) const { (void)x; }
    virtual ~Base() = default;
};

struct Derived : Base {
    using Base::log;
    void log(double d) const { (void)d; }
private:
    void log(int x = 99) const override { (void)x; } // private + different default
};

void dispatch(const Base& b) {
    b.log(); // calls Derived::log(10): public via Base, default 10 via Base
}
```

> **Pitfall.** Making an overriding function `private` in `Derived` does not block callers using a `Base&` or `Base*`, and overriding a default argument in `Derived` has zero effect when invoked polymorphically through `Base`. Keep virtual overrides at matching access and avoid default arguments on virtual functions altogether.

The static-versus-dynamic split across every rule of a virtual call is compactly summarized in this lookup matrix:

| Call property | Resolved from | Reason in standard |
| --- | --- | --- |
| Unqualified name lookup | Static type | Scopes checked at compile time |
| Access check (`public`/`private`) | Static type | Checked at call site expression |
| Default argument value | Static type | Substituted at compile time |
| Target function body | Dynamic type | Dispatched via virtual override |

## Virtual destructors and virtual dispatch in constructors

Deleting a derived object through a `Base*` when `Base::~Base()` is non-virtual triggers **undefined behavior** (`[expr.delete]`), not merely an incomplete destructor call. A polymorphic base class designed for owning deletion through base pointers must declare a `public` `virtual` destructor (`virtual ~Base() = default;`). Conversely, a non-polymorphic mixin or base class that forbids deletion via `Base*` should make its destructor `protected` and non-virtual. Note that a pure virtual destructor (`virtual ~Base() = 0;`) still requires a body (`Base::~Base() {}`), because every derived destructor automatically invokes its base destructor during teardown.

Equally critical is what happens while a constructor or destructor runs.

> **Standardese.** Under `[class.cdtor]`, during execution of `Base`'s constructor or destructor, the dynamic type of the object under construction or destruction is `Base`—not `Derived`.

Because `Derived`'s members are not yet constructed during `Base::Base()` (and have already been destroyed before `Base::~Base()`), C++ locks the `vptr` to `Base` while `Base`'s constructor or destructor runs. Calling a virtual function from `Base::Base()` invokes `Base`'s own implementation rather than `Derived`'s override, and calling a pure virtual function without qualification during construction or destruction causes undefined behavior.

## Multiple inheritance, virtual bases, and RTTI

Non-virtual diamond inheritance (`Left : Base`, `Right : Base`, `Join : Left, Right`) places two separate `Base` subobjects inside `Join`, making conversions from `Join*` to `Base*` ambiguous. Inheriting `virtual Base` (`Left : virtual Base`, `Right : virtual Base`) merges them into a single shared subobject, typically accessed at runtime via a compiler-generated offset table inside the vtable.

With virtual inheritance, **the most-derived class initializes every virtual base directly** (`[class.base.init]`). When constructing `Join`, `Join`'s member-initializer list constructs `Base`, and any `Base(...)` initializers written in `Left` or `Right` are skipped entirely—even if `Join` omits `Base(...)` and relies on default initialization.

At runtime, two RTTI operators inspect polymorphic objects whose static type is a base class:

- `dynamic_cast<Target*>(ptr)` walks the dynamic object's RTTI graph safely across **downcasts** (`Base*` to `Derived*`) and **cross-casts** (`Left*` to sibling `Right*` inside `Join`), returning `nullptr` if the cast fails; `dynamic_cast<Target&>(ref)` throws `std::bad_cast` on failure (`[expr.dynamic.cast]`).
- `typeid(*ptr)` evaluates the dynamic `std::type_info` only when `*ptr` is a glvalue of polymorphic class type (`[expr.typeid]`), throwing `std::bad_typeid` if `ptr` is null; for non-polymorphic expressions, `typeid` evaluates only the static type and does not evaluate its operand.

## What to remember

- Inheritance embeds `Base` subobjects inside `Derived`; passing by value slices `Derived` and strips polymorphism.
- Always use `override` on overrides and `final` when sealing interfaces; pure virtuals (`= 0`) can still have definitions.
- Access control, name lookup, and default arguments bind to the **static type**, whereas virtual dispatch selects the **dynamic type**'s overrider.
- Deleting a derived object via a non-virtual base destructor is undefined behavior; make polymorphic base destructors `public virtual` (or non-polymorphic base destructors `protected` non-virtual).
- Inside `Base`'s constructor and destructor, the dynamic type is `Base`, never `Derived`; in virtual inheritance, the most-derived constructor initializes the virtual base directly.

## Concept Map Outline

- **Inheritance & Virtuals:** C++ separates embedded subobject layout and compile-time lookup rules from runtime virtual dispatch.
  - **Object Layout:** Derived objects embed base subobjects contiguously in memory rather than holding hidden heap pointers.
    - **Embedded Base Subobject:** Every Derived instance stores its Base subobjects directly inside its own footprint.
    - **Object Slicing:** Passing Derived by value copies only the Base subobject and resets the dynamic type to Base.
    - **Pointer Adjustment:** Converting a non-null derived pointer to a secondary base shifts the address by that base offset.
    - **Virtual Bases:** Virtual inheritance merges diamond bases into one subobject initialized by the most-derived class.
  - **Virtual Dispatch:** Polymorphic classes select overriders at runtime using the dynamic type rather than the pointer type.
    - **Static vs Dynamic Type:** Expressions carry a fixed compile-time static type while pointers and references point to a dynamic type.
    - **vptr and vtable:** Each polymorphic object holds a vptr pointing to its class vtable of virtual function entries.
    - **override and final:** These specifiers catch signature mismatches at compile time and enable devirtualization.
    - **Pure Virtual Functions:** Marking a virtual function pure makes the class abstract while still allowing a qualified definition.
  - **Lookup & Access:** Name hiding, access specifiers, and default arguments resolve statically before virtual dispatch runs.
    - **Name Hiding:** Declaring any same-named member in Derived hides all Base overloads unless brought in with using.
    - **Static Access Check:** Access rules on a virtual call are enforced against the static type at the call site.
    - **Static Default Args:** Default argument expressions come from the static receiver type even when a derived override executes.
  - **Lifetime Boundaries:** Polymorphic deletion and constructor or destructor execution obey strict dynamic-type boundaries.
    - **Virtual Destructors:** Deleting Derived through a non-virtual Base destructor is undefined behavior rather than a partial free.
    - **Ctor and Dtor Dispatch:** During Base construction or destruction the object's dynamic type is Base, preventing derived dispatch.
  - **RTTI & Casts:** Runtime type identification inspects polymorphic objects for safe downcasts and cross-casts.
    - **dynamic_cast:** Navigates polymorphic hierarchies safely, returning null for invalid pointers or throwing bad_cast for references.
    - **typeid Operator:** Evaluates the dynamic type_info for dereferenced polymorphic pointers and throws bad_typeid on null.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.delete], [class.dtor])

What happens when a caller deletes a Derived object through a Base* pointer whose ~Base() destructor is NOT virtual?

```cpp
struct Base {
    ~Base() {}
};
struct Derived : Base {
    std::string data = "owned";
};
void destroy() {
    Base* p = new Derived{};
    delete p;
}
```

A. Only ~Base() runs and Derived::data leaks, which is otherwise well-defined
B. Both ~Derived() and ~Base() run because operator delete checks heap metadata
C. The behavior is undefined according to [expr.delete]
D. The compiler rejects delete p unless Base has at least one virtual function

**Answer (C):** The behavior is undefined according to [expr.delete]

**Why:** Under [expr.delete], deleting a polymorphic or derived-class object through a base pointer whose static type has a non-virtual destructor is undefined behavior—even if Derived adds no non-trivial data members.

### Question 2 [warmup] ([class.virtual], [dcl.fct])

Why does omitting the override specifier on Derived::render below introduce a subtle bug?

```cpp
struct Widget {
    virtual void render(int dpi) const;
};
struct Button : Widget {
    void render(int dpi);
};
```

A. Button::render lacks const, so it hides Widget::render instead of overriding it
B. Virtual functions cannot be overridden without repeating the virtual keyword
C. The compiler automatically converts Widget::render to non-const to match Button
D. Button becomes an abstract class until override is added

**Answer (A):** Button::render lacks const, so it hides Widget::render instead of overriding it

**Why:** const-qualification is part of a member function's type. Without override, Button::render(int) declares a brand-new unrelated non-virtual member that hides Widget::render(int) const rather than overriding it.

### Question 3 [tricky] ([class.access.virt], [class.virtual])

What is the result of compiling and calling probe()?

```cpp
struct Base {
    virtual int value(int x = 10) const { return x; }
    virtual ~Base() = default;
};
struct Derived : Base {
private:
    int value(int x = 99) const override { return x + 1; }
};
int probe() {
    Derived d;
    const Base& b = d;
    return b.value();
}
```

A. Compile error: Derived::value is private
B. Returns 100 because Derived::value runs with Derived's default argument 99
C. Returns 10 because virtual calls with private overrides fall back to Base
D. Compiles and returns 11: access and default arg use Base, dispatch uses Derived

**Answer (D):** Compiles and returns 11: access and default arg use Base, dispatch uses Derived

**Why:** Access control ([class.access.virt]) and default arguments ([dcl.fct.default]) are checked and substituted statically from Base at the call site b.value(). At runtime, virtual dispatch still invokes Derived::value(10), returning 11.

### Question 4 [tricky] ([class.cdtor])

What does constructing Derived log when Base's constructor calls the virtual function tag()?

```cpp
struct Base {
    Base() { log(tag()); }
    virtual ~Base() = default;
    virtual const char* tag() const { return "Base"; }
};
struct Derived : Base {
    const char* tag() const override { return "Derived"; }
};
```

A. "Derived", because the dynamic type of the full object is already Derived
B. "Base", because inside Base::Base() the object's dynamic type is Base
C. Undefined behavior whenever any virtual function is called from a constructor
D. Compile error: virtual functions cannot be called inside constructors

**Answer (B):** "Base", because inside Base::Base() the object's dynamic type is Base

**Why:** Under [class.cdtor], while Base::Base() executes, Derived's subobject has not started its lifetime yet, so the dynamic type of *this is Base. Virtual dispatch therefore resolves tag() to Base::tag().

### Question 5 [standardese] ([class.base.init], [class.mi])

In virtual diamond inheritance below, what value does Join{}.id hold after construction?

```cpp
struct Common {
    int id;
    explicit Common(int i = 0) : id(i) {}
};
struct Left : virtual Common { Left() : Common(1) {} };
struct Right : virtual Common { Right() : Common(2) {} };
struct Join : Left, Right {
    Join() : Left(), Right() {}
};
```

A. 0, because the most-derived class Join initializes Common and omits Common from its initializer list
B. 1, because Left appears first in Join's base-specifier list
C. 2, because Right overwrites Common after Left runs
D. Ill-formed: Join fails to compile unless it explicitly writes Common(0)

**Answer (A):** 0, because the most-derived class Join initializes Common and omits Common from its initializer list

**Why:** Under [class.base.init], a virtual base subobject is always initialized by the constructor of the most-derived class (Join). Initializers for Common in Left and Right are ignored, so Join default-initializes Common via Common(0).

### Question 6 [standardese] ([class.dtor], [class.abstract])

Why does declaring a pure virtual destructor `virtual ~Stream() = 0;` still require providing an out-of-class body `Stream::~Stream() = default;`?

```cpp
struct Stream {
    virtual ~Stream() = 0;
};
struct FileStream : Stream {};
```

A. Only because linkers always emit vtable slots for destructors even on abstract classes
B. Because pure virtual functions can never have empty bodies in C++
C. Because FileStream's destructor implicitly invokes Stream::~Stream() non-virtually during teardown
D. It is optional unless a caller deletes through Stream*

**Answer (C):** Because FileStream's destructor implicitly invokes Stream::~Stream() non-virtually during teardown

**Why:** Every derived destructor implicitly calls each direct base class's destructor statically (not via virtual dispatch) when tearing down the base subobject ([class.dtor]). Without a definition for Stream::~Stream(), linking FileStream fails.
