# Multiple and virtual inheritance

> With several bases, a derived object holds several base subobjects at different addresses, so conversions may move the pointer and names may be ambiguous. Virtual inheritance shares one base subobject among all paths, at the price of most-derived initialization and run-time located bases.

- **Source:** C++ Atlas (https://cppatlas.com/topics/multiple-and-virtual-inheritance)
- **Track:** Classes
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [class.mi] (https://eel.is/c++draft/class.mi), [class.member.lookup] (https://eel.is/c++draft/class.member.lookup), [class.base.init] (https://eel.is/c++draft/class.base.init), [class.virtual] (https://eel.is/c++draft/class.virtual), [conv.ptr] (https://eel.is/c++draft/conv.ptr), [expr.static.cast] (https://eel.is/c++draft/expr.static.cast), [expr.reinterpret.cast] (https://eel.is/c++draft/expr.reinterpret.cast), [expr.dynamic.cast] (https://eel.is/c++draft/expr.dynamic.cast), [basic.compound] (https://eel.is/c++draft/basic.compound), [intro.object] (https://eel.is/c++draft/intro.object), [expr.cast] (https://eel.is/c++draft/expr.cast)
- **cppreference links:** [Derived classes (virtual base classes)](https://en.cppreference.com/w/cpp/language/derived_class), [static_cast conversion](https://en.cppreference.com/w/cpp/language/static_cast), [reinterpret_cast conversion](https://en.cppreference.com/w/cpp/language/reinterpret_cast), [dynamic_cast conversion](https://en.cppreference.com/w/cpp/language/dynamic_cast), [Empty base optimization](https://en.cppreference.com/w/cpp/language/ebo)
- **Prerequisites:** inheritance-and-virtual-functions, constructors-and-initialization-order, casts, object-layout-and-alignment

## The one idea

A class with several bases contains one subobject per non-virtual base, each at its own place inside the object. Converting a pointer from the derived class to a base means finding that subobject, and in general that changes the address. A virtual base is different: however many paths lead to it, the most derived object contains exactly one, shared subobject, whose position is only known at run time.

Most of the rules follow from that picture. Names found in two different subobjects are ambiguous. Casts that know the class relationship adjust pointers, while casts that do not, such as `reinterpret_cast`, do not. And because a shared virtual base belongs to no single path, only the most derived class can initialize it.

> **Mental model.** A pointer to a base is a pointer to a particular subobject, not to the whole object. Any cast that does not know the inheritance graph cannot find the right subobject.

## Several base subobjects and pointer adjustment

Take `struct C : A, B { ... };`. A `C` object contains an `A` subobject and a `B` subobject, and the standard does not say where. Typical implementations put `A` at offset zero and `B` after it, so `static_cast<B*>(&c)`, or the implicit conversion, adds an offset to the address.

The compiler applies the offset in both directions because it knows the class graph. Converting `B*` back to `C*` with `static_cast` subtracts it, and a null pointer stays null in both directions. Comparing a `B*` with a `C*` converts the `C*` to `B*` first, so the comparison is true for the same object even though the raw addresses differ.

```cpp
#include <cstdio>

struct A { int a = 1; };
struct B { int b = 2; };
struct C : A, B { int c = 3; };

int main() {
  C c;
  B* pb = &c;                       // adjusted to the B subobject
  C* p1 = static_cast<C*>(pb);      // adjusted back: p1 == &c
  std::printf("%d %d\n", pb == &c, p1->c);   // 1 3, guaranteed
  // C* p2 = reinterpret_cast<C*>(pb);  // not adjusted: p2 still points at the B
  //                                    // subobject, so p2->c is undefined behavior
}
```

`reinterpret_cast` between object pointer types is specified as a round trip through `void*`. Converting from `void*` only yields a pointer to a different object when the two objects are **pointer-interconvertible**, which a class and its second base are not. So the value is unchanged: a `C*` that points at a `B`. The same trap catches code that stores a `B*` in a `void*` and later casts the `void*` to `C*`. C-style casts are exposed too: when either class is incomplete at the cast, [expr.cast] leaves it unspecified whether the `static_cast` or the `reinterpret_cast` meaning is used.

> **Pitfall.** Round-trip through `void*` only with the exact type you started from. Store a `B*`, get back a `B*`, then `static_cast` to `C*` if you must.

## Ambiguity and name lookup

Member name lookup in a class with several bases looks in each base and merges the results. If the name is found in two different base subobjects, the lookup is ambiguous, and the program is ill-formed when the name is used. This happens **before** overload resolution, so different parameter lists do not help.

```cpp
struct Reader { void put(int) {} };
struct Writer { void put(double) {} };
struct Device : Reader, Writer {
  // using Reader::put; using Writer::put;   // uncomment to overload them
};

void use(Device& d) {
  // d.put(1);          // ill-formed: put is found in two base classes
  d.Reader::put(1);     // OK: qualified name picks the subobject
}
```

Two using-declarations bring both sets into the derived scope, after which ordinary overload resolution applies. Static members, nested types and enumerators found through several paths are not ambiguous when they denote the same entity, because no particular subobject is needed.

## The diamond and virtual base classes

If `Left` and `Right` both derive from `Top`, and `Bottom` derives from both, a `Bottom` contains two `Top` subobjects. Converting `Bottom*` to `Top*` is ambiguous, and a member of `Top` must be reached through `Left::` or `Right::`.

```text
non-virtual                      virtual

  Top     Top                       Top
   |       |                       /   \
  Left   Right                  Left   Right
     \   /                         \   /
     Bottom                        Bottom
two Top subobjects              one shared Top
```

Declaring the base `virtual`, as in `struct Left : virtual Top`, makes all virtual occurrences of `Top` in a most derived object share one subobject. The conversion to `Top*` is then unambiguous, and `Top`'s constructor runs once.

Shared bases also create **dominance**. A name declared in a derived class hides the same name in a base, and with a shared virtual base that holds across paths: if `Left` declares `f` and `Top` declares `f`, then in `Bottom` the name `Left::f` dominates `Top::f`, even though `Right` sees only `Top::f`. With non-virtual inheritance the same shape is ambiguous, because `Right`'s `Top` is a different subobject.

For virtual functions, the final overrider must be unique. If both `Left` and `Right` override a virtual function of a shared `Top`, `Bottom` must override it too, or the class is ill-formed.

## Who initializes a virtual base

Because the shared subobject belongs to no single path, [class.base.init] gives its initialization to the **most derived class**. Mem-initializers naming a virtual base in intermediate classes are ignored when those classes are not the most derived. If the most derived class does not name the virtual base, the virtual base is default-initialized, and the program is ill-formed if it has no default constructor.

```cpp
#include <cstdio>

struct Top { Top(int v) { std::printf("Top %d\n", v); } };
struct Left  : virtual Top { Left()  : Top(1) {} };
struct Right : virtual Top { Right() : Top(2) {} };
struct Bottom : Left, Right {
  Bottom() : Top(3) {}   // required: Top has no default constructor
};

int main() { Bottom b; }   // prints Top 3; Top(1) and Top(2) are ignored
```

Virtual bases are also constructed first, before any non-virtual base, in the order of a depth-first, left-to-right walk of the base class graph. For `struct M : N, L, R` where only `L` and `R` derive virtually from `V`, the constructors run in the order `V`, `N`, `L`, `R`, `M`, and destruction reverses it.

> **Standardese.** [class.base.init] says that a mem-initializer whose mem-initializer-id denotes a virtual base class is ignored during execution of a constructor of any class that is not the most derived class.

## Casts across the graph and empty bases

`static_cast` can convert down from a non-virtual base, unchecked. It cannot convert down from a virtual base, and the program is ill-formed if you try, because the position of the virtual base relative to the derived class is not a compile-time constant. `dynamic_cast` handles that case, and it can also **cross-cast** sideways: given an `A*` that points into a `C : A, B`, `dynamic_cast<B*>` finds the `B` subobject of the same most derived object, or returns null if there is no unique public one. `dynamic_cast<void*>` returns the address of the most derived object. Downcasts, cross-casts and casts to `void*` all need a polymorphic source type.

```cpp
struct A { virtual ~A() = default; };
struct B { virtual ~B() = default; };
struct C : A, B {};

B* sideways(A* pa) {
  return dynamic_cast<B*>(pa);   // non-null when *pa is part of a C
  // static_cast<B*>(pa) is ill-formed: A and B are unrelated
}
```

Empty base classes may occupy no storage, the empty base optimization, which the topic on object layout and alignment covers. Multiple inheritance adds one constraint: two subobjects of the same type must have distinct addresses, per [intro.object]. An empty base cannot share its address with a member or another base of the same type, so the optimization quietly turns off in that case.

## Layout: ABI practice, not the standard

> **Mental model.** Everything in this section is implementation practice under the Itanium C++ ABI used by GCC and Clang on Linux and macOS, not a guarantee. MSVC differs in detail.

The first non-virtual polymorphic base is the **primary base**: it lives at offset zero and shares the object's vptr. Every other polymorphic base subobject has its own vptr pointing into a secondary vtable. When you call a virtual function through a `B*` and `C` overrides it, the `B` vtable slot points to a small **thunk** that subtracts the offset to get `this` back to the start of the `C` before jumping to `C`'s function.

A virtual base sits at an offset that depends on the most derived class, so the vtable stores a **virtual base offset**, and converting to a virtual base loads that offset at run time. During construction, intermediate classes use special construction vtables with offsets that suit the partially built object. MSVC instead stores a separate virtual base table pointer in the object. These differences are why mixing compilers across a class hierarchy needs a shared ABI, and why size or offset numbers are never portable facts.

## What to remember

- Each non-virtual base is its own subobject; converting to most bases changes the pointer value.
- `static_cast` and implicit conversions adjust pointers; `reinterpret_cast` and round trips through `void*` with a different type do not.
- Lookup that finds a name in two base subobjects is ambiguous before overload resolution; qualify it or add using-declarations.
- A non-virtual diamond has two top subobjects; virtual inheritance shares one.
- In a virtual diamond, a derived declaration dominates the virtual base's, and a virtual function needs a unique final overrider.
- Only the most derived class initializes a virtual base; intermediate mem-initializers for it are ignored.
- Virtual bases are built first, depth-first and left to right.
- `static_cast` cannot go down from a virtual base; `dynamic_cast` can, and can cross-cast.
- Two subobjects of the same type never share an address, which can disable the empty base optimization.
- Thunks, primary bases and virtual base offsets are ABI practice, not standard guarantees.

## Concept Map Outline

- **Multiple and virtual inheritance:** One subobject per non-virtual base; one shared subobject per virtual base.
  - **Pointer adjustment:** A base pointer points at a subobject, often at a different address.
    - **static_cast adjusts:** Implicit and static conversions add or subtract the base offset; null stays null.
    - **reinterpret_cast does not:** C* from a second-base B* still points at the B; using it as a C is undefined.
    - **Comparison converts:** pb == &c converts &c to B* first, so it is true for the same object.
    - **void* round trips:** Cast back only to the exact type you stored.
  - **Name lookup:** Lookup merges results from every base before overload resolution.
    - **Ambiguity:** A name found in two different base subobjects is ill-formed to use.
    - **Qualify or using:** d.Reader::put picks one; two using-declarations make them overload.
    - **Same entity is fine:** Static members, types and enumerators found via several paths are not ambiguous.
    - **Dominance:** With a shared virtual base, a derived declaration wins over the base's.
  - **The diamond:** Two paths to the same base class.
    - **Non-virtual:** Two Top subobjects; converting Bottom* to Top* is ambiguous.
    - **Virtual:** One shared Top; its constructor runs once.
    - **Unique final overrider:** If two paths override a shared base's virtual, the most derived must override too.
  - **Virtual base initialization:** The most derived class owns the shared base's construction.
    - **Intermediates ignored:** Mem-initializers for a virtual base run only in the most derived constructor.
    - **Default otherwise:** If the most derived class omits it, the base is default-initialized or ill-formed.
    - **Constructed first:** Virtual bases precede all non-virtual bases, depth-first and left to right.
  - **Casts across the graph:** Which cast can navigate which edge.
    - **No static downcast:** static_cast from a virtual base to a derived class is ill-formed.
    - **dynamic_cast cross-cast:** Moves sideways from A* to B* inside the same most derived object.
    - **dynamic_cast to void*:** Returns the address of the most derived object.
    - **Distinct addresses:** Two subobjects of the same type never share an address, limiting EBO.
  - **Layout (ABI practice):** Itanium ABI details, not standard guarantees.
    - **Primary base:** The first non-virtual polymorphic base sits at offset zero and shares the vptr.
    - **Thunks:** Secondary vtable slots adjust this before jumping to the override.
    - **Virtual base offset:** Stored in the vtable and loaded at run time; MSVC uses a vbptr instead.

## Standardese Quiz Questions

### Question 1 [warmup] ([conv.ptr], [class.mi], [class.member.lookup])

Is this program well-formed?

```cpp
struct Top { int t = 0; };
struct Left  : Top {};
struct Right : Top {};
struct Bottom : Left, Right {};

int main() {
  Bottom b;
  Top* p = &b;
  (void)p;
}
```

A. Well-formed: `p` points to the `Top` inside `Left`, the first base
B. Ill-formed: `Top` is an ambiguous base of `Bottom`
C. Well-formed, but which `Top` is chosen is unspecified
D. Undefined behavior

**Answer (B):** Ill-formed: `Top` is an ambiguous base of `Bottom`

**Why:** Without virtual inheritance, a `Bottom` contains two distinct `Top` subobjects, one through `Left` and one through `Right`. The derived-to-base conversion must identify a unique subobject, so it is ill-formed. There is no rule preferring the first base; write `static_cast<Left*>(&b)` first, or make `Top` a virtual base.

### Question 2 [warmup] ([class.base.init], [class.mi])

What does this program print?

```cpp
#include <cstdio>

struct V { V() { std::puts("V"); } };
struct N { N() { std::puts("N"); } };
struct L : virtual V { L() { std::puts("L"); } };
struct R : virtual V { R() { std::puts("R"); } };
struct M : N, L, R { M() { std::puts("M"); } };

int main() { M m; }
```

A. `N V L R M`
B. `V L V R N M`
C. `N V L V R M`
D. `V N L R M`

**Answer (D):** `V N L R M`

**Why:** The most derived class constructs its virtual bases first, before any non-virtual base, so the single shared `V` comes before `N` even though `N` is listed first. Then the direct bases run in declaration order, `N`, `L`, `R`, and finally the body of `M`. `V` appears once because both paths share one virtual base subobject, which rules out the options with two `V` lines.

### Question 3 [warmup] ([expr.eq], [conv.ptr])

What does this program print?

```cpp
#include <cstdio>

struct A { int a = 1; };
struct B { int b = 2; };
struct C : A, B { int c = 3; };

int main() {
  C c;
  B* pb = &c;
  std::printf("%d\n", pb == &c);
}
```

A. `0`, because `pb` points past the `A` subobject
B. `1`
C. Either `0` or `1`; the layout is implementation-defined
D. Ill-formed: `B*` and `C*` cannot be compared

**Answer (B):** `1`

**Why:** Comparing `B*` with `C*` first converts `&c` to `B*` with the usual derived-to-base pointer conversion, which yields the address of the same `B` subobject `pb` points to. The comparison is therefore true regardless of layout. Converting both to `void*` first would compare raw addresses, and that result does depend on the implementation.

### Question 4 [tricky] ([class.member.lookup], [namespace.udecl])

Is this program well-formed?

```cpp
struct Reader { void put(int) {} };
struct Writer { void put(double) {} };
struct Device : Reader, Writer {};

int main() {
  Device d;
  d.put(1);
}
```

A. Well-formed: overload resolution picks `Reader::put(int)`, the exact match
B. Well-formed: the first base listed wins
C. Ill-formed: the conversion from `Device` to `Writer` is ambiguous
D. Ill-formed: the name `put` is ambiguous

**Answer (D):** Ill-formed: the name `put` is ambiguous

**Why:** Member name lookup runs before overload resolution. It finds `put` in two different base class subobjects, so the lookup result is ambiguous and the program is ill-formed, whatever the argument types. The first option is how people expect overloading to work; it does once `Device` declares `using Reader::put; using Writer::put;`.

### Question 5 [tricky] ([class.base.init])

What does this program print?

```cpp
#include <cstdio>

struct Top { Top(int v) { std::printf("Top %d\n", v); } };
struct Left  : virtual Top { Left()  : Top(1) {} };
struct Right : virtual Top { Right() : Top(2) {} };
struct Bottom : Left, Right { Bottom() : Top(3) {} };

int main() { Bottom b; }
```

A. `Top 1`
B. `Top 1` then `Top 2`
C. `Top 3`
D. Ill-formed: `Top` is initialized by more than one constructor

**Answer (C):** `Top 3`

**Why:** A virtual base is initialized by the most derived class, here `Bottom`, using its mem-initializer `Top(3)`. The mem-initializers `Top(1)` in `Left` and `Top(2)` in `Right` are ignored because those constructors are not running for the most derived object. `Top 1` is the tempting answer for anyone who expects the first base on the path to win.

### Question 6 [tricky] ([expr.reinterpret.cast], [expr.static.cast], [basic.compound])

What does the standard say about this program?

```cpp
#include <cstdio>

struct A { int a = 1; };
struct B { int b = 2; };
struct C : A, B { int c = 3; };

int main() {
  C c;
  B* pb = &c;
  C* p = reinterpret_cast<C*>(pb);
  std::printf("%d\n", p->c);
}
```

A. It prints `3`, the same as with `static_cast`
B. Undefined behavior
C. Ill-formed: `reinterpret_cast` cannot convert between related classes
D. It prints an implementation-defined value

**Answer (B):** Undefined behavior

**Why:** `reinterpret_cast` between object pointers behaves like `static_cast` through `void*`, and that only lands on a different object when the two are pointer-interconvertible. A class is not pointer-interconvertible with its second base, so `p` still points at the `B` subobject, and accessing `p->c` as if it were a `C` is undefined behavior. `static_cast<C*>(pb)` would subtract the base offset and print 3, which is why the first option is tempting. The cast itself compiles.

### Question 7 [standardese] ([class.member.lookup])

What does `run()` return?

```cpp
struct Top   { int f() { return 1; } };
struct Left  : virtual Top { int f() { return 2; } };
struct Right : virtual Top {};
struct Bottom : Left, Right {};

int run() {
  Bottom b;
  return b.f();
}
```

A. 2
B. 1
C. Ill-formed: `f` is ambiguous between `Left::f` and `Top::f`
D. Unspecified: it depends on the order of the base classes

**Answer (A):** 2

**Why:** Lookup in `Bottom` finds `Left::f` through `Left` and `Top::f` through `Right`. Because `Top` is a virtual base, the `Top` subobject seen through `Right` is the same one that is a base of `Left`, so [class.member.lookup] discards `Top::f` in favour of `Left::f`; this is dominance. If `Top` were a non-virtual base, the two declarations would be in unrelated subobjects and the call would be ambiguous, which is why the third option is tempting.

### Question 8 [standardese] ([expr.static.cast], [expr.dynamic.cast])

Which conversion in `down` is ill-formed?

```cpp
struct V { virtual ~V() = default; };
struct W : virtual V {};

void down(V* pv) {
  W* a = dynamic_cast<W*>(pv);   // A
  W* b = static_cast<W*>(pv);    // B
  (void)a; (void)b;
}
```

A. A, because `dynamic_cast` cannot go through a virtual base
B. B, because `static_cast` cannot convert from a virtual base to a derived class
C. Both A and B
D. Neither; both compile, and B is undefined behavior if `*pv` is not a `W`

**Answer (B):** B, because `static_cast` cannot convert from a virtual base to a derived class

**Why:** [expr.static.cast] allows a downcast from `B*` to `D*` only if `B` is neither a virtual base of `D` nor a base of a virtual base of `D`. The offset from a virtual base to the derived class depends on the most derived object, so a static conversion cannot compute it and B is ill-formed. `dynamic_cast` reads it from the object at run time and is well-formed here. The last option describes downcasting from a non-virtual base.
