Multiple inheritance
hard 50 minA 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.
#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}The 40 bytes of Both
| Offset | Content | Belongs to |
|---|---|---|
| 0 | pointer to a method table | Left, and Both |
| 8 | a | Left |
| 16 | pointer to a second method table | Right |
| 24 | b | Right |
| 32 | c | Both |
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 throughvoid*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