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

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Two parents: two names to settle and one tank to share.

A bus that is also a boat. Two HORN buttons are the clash, two tanks are the copied state, one tank is the shared ancestor, and a car with a boat trailer is composition.

Cheat sheet

Type, behaviour, state
easy, needs an order, needs a plan
Python
MRO, super() is next in line
C++
ambiguity is an error; `virtual` shares
Java and C#
one class, many interfaces
TypeScript
mixin functions, one chain
Ruby and PHP
modules, traits
Constructor rule
keywords, take yours, pass rest, call super
Mixin place
left
Join classes for n sides
2 to the power n, minus n, minus 1

Spot it when you see

  • It is both an X and a Y
  • Framework with mixins
  • AttributeError for a field that a parent should set
  • A method that is never reached
  • Two libraries with the same method name

Tricks that stick

  • Same word or same promise? Ask it for each shared name.
  • TAPS: Take yours, All keywords, Pass the rest, Super always.
  • Parents are for life. If it can end, it is a role.

Do not forget

  • Positional constructor arguments
  • A parent that does not call super
  • Calling a parent by name in a join
  • Mixin on the right
  • Casting through void pointers in C++