AlgoViz

Multiple inheritance

hard 50 min

A class with several parent classes gets the types, the methods and the fields of all of them.

Watch lesson4:37

Memory and cost

What C++ does with two parents.

The point: an object with two bases contains two complete subobjects. A pointer to the second base is a different address.

C++
#include <cstdint>#include <iostream>struct Left  { virtual ~Left() = default;  virtual int left()  { return 1; } long a = 1; };struct Right { virtual ~Right() = default; virtual int right() { return 2; } long b = 2; };struct Both : Left, Right { long c = 3; };int main() {    Both both;    Left* l = &both;    Right* r = &both;    auto at = [](void* p) { return reinterpret_cast<std::uintptr_t>(p); };    std::cout << "size " << sizeof(Both) << '\n';             // 40    std::cout << "left at +" << at(l) - at(&both) << '\n';    // 0    std::cout << "right at +" << at(r) - at(&both) << '\n';   // 16    std::cout << (r == &both) << '\n';                        // 1: compared after adjustment    void* raw = r;    std::cout << (raw == static_cast<void*>(&both)) << '\n';  // 0: raw addresses differ}
Run with clang on a 64 bit machine. The numbers in comments are the output.

The 40 bytes of Both

OffsetContentBelongs to
0pointer to a method tableLeft, and Both
8aLeft
16pointer to a second method tableRight
24bRight
32cBoth
Two table pointers: one more than with a single parent. A call through Right& must find the start of Both again, and the second table contains a small helper (a thunk) that moves the pointer back by 16.

Consequences

What this changes in your code

Four consequences

  • Converting can change the address

    Left* and Right* to one object differ. Comparing them with == adjusts first. Comparing through void* does not.

  • Never cast through void*

    Both* to void* to Right* gives a wrong pointer. Cast to Right* first.

  • A virtual destructor in every base

    Deleting through Right* must reach the start of the object.

  • The price is small

    One more pointer per base with virtual functions, and an addition for some calls. Clarity is the bigger cost.

Empty bases without virtual functions usually cost nothing. Virtual bases cost more, because their place is found at run time: see Diamond problem. How tables work at all is in Polymorphism under the hood. In Python an object is one dictionary, so nothing of this exists there; its price is a search along the MRO, which the interpreter caches.

A call through the second base

The helper is needed only if Both overrides the function.