AlgoViz

Multiple inheritance

hard 50 min

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

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:37

Multiple inheritance

1:01Reel

Theory

Read or listen first. About 2 min.

What it is

Multiple inheritance means that a class names more than one direct parent class: class WorkingStudent(Student, Employee). An object of it is a student and an employee at once, and it has the methods and fields of both.

It helps to split it in three. Multiple inheritance of type (many interfaces) exists in nearly every language. Of behaviour (methods with bodies) exists in many, as default methods, traits or mixins. Of state (fields and constructors) exists in few, such as C++, Python and Eiffel. Nearly all the trouble comes from state.

This page is about the feature itself: what a language must decide, how to write parents that get along, and when to choose something else. Two neighbours have pages of their own: the shared ancestor is in Diamond problem, and life without the feature is in Multiple parents in single inheritance.

Why it exists

Some things really have several independent sides. A threaded web server is a web server and is threaded. A product can be saved, has a price and has a label. One tree cannot show independent sides without copies.

Code can come from several sources without forwarding lines. class ThreadingHTTPServer(ThreadingMixIn, HTTPServer) is a whole class in one line.

And the type system sees it: the object can be handed to code that wants either parent.

A short history

  1. 1980

    The Flavors system of the MIT Lisp Machine (A.I. Memo 602, November) builds classes by mixing several flavors.

  2. 1989

    C++ 2.0 adds multiple inheritance, together with abstract classes.

  3. 1996

    Java 1.0 leaves it out. The language white paper says that multiple inheritance and the problems it generates were discarded, and that interfaces bring its desirable features.

  4. 2014

    Java 8 lets interfaces have method bodies: behaviour from many sources comes back, state does not.

Words to know

Direct base
A parent named in the class header.
Join class
The class where several parents meet.
MRO
Method resolution order: the line of classes that Python searches for a name.
Cooperative method
It does its own share and calls super(), so every class in the line gets its turn.
Mixin
A small parent made to be combined, not to stand alone.
Name clash
Two parents have a member with one name.
Subobject
In C++, the part of an object that belongs to one base class.
Pointer adjustment
Moving an address from the whole object to one of its subobjects.
Virtual base
In C++, a base that is shared instead of repeated.
Orthogonal
Independent: one side can change without the other.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Name the sides. Independent, small, and for life?

Understand it

Start here

A bus that is also a boat

Noor drives tourists through a town by the lake. A bus is good on the road, a boat is good on the water. So the town builds something that is both.

Noor and the swimming bus

Frames 3 and 4 are the two prices of two parents: names and state. Frames 5 to 7 are three ways to pay.

Structure

Person, student, employee

The classic example. A working student studies at a school and works at a company. First as many people write it, then as it should be.

Bad: two persons in one student (C++ without virtual)

Person# namePerson# nameStudent# school+ study()Employee# company+ work()

1/3Two good classes

A student is a person. An employee is a person. Each carries the fields of a person.

extends (is a)

The same class drawn twice, because the object contains it twice.

Good: one person, two sides

Person# name+ eat()+ describe()

1/4One root

Person owns the name. Nobody below stores a second one.

extends (is a)

Who is called by super() in describe

Student does not name Employee and is not its child. super() means the next class in the order of this object.

Languages

Who supports what

LanguageMany parent classesHowA clash of names
C++yesFull; virtual bases share an ancestorError at the call, unless you qualify
PythonyesFull; a search order, the MROFirst in the order wins, silently
EiffelyesFull; parents can be adaptedMust be renamed
JavanoOne class, many interfaces with defaultsCompile error, you must override
C#noOne class, many interfacesError, or implement each separately
TypeScriptnoOne class, many interfaces, mixin functionsThe last applied mixin wins
RubynoOne class, modules are includedThe last included module wins
PHPnoOne class, traitsError until insteadof chooses
Two families: languages that pick by a rule (Python, Ruby), and languages that make you say it (C++, Java, Eiffel, PHP).

What you win

  • Code from several sources without forwarding
  • Things with two sides, such as a working student
  • Types that fit in more than one place
  • Independent features combined in one line

What you pay

  • Ambiguity when an ancestor is shared
  • Names that clash
  • The order of parents is part of the meaning
  • Harder to see where a method comes from

Rule 1

Order is meaning

In Python the class on the left is searched first. A mixin that wraps a method must stand left of the class it wraps. Python's own socketserver page says it: the mix-in class comes first, since it overrides a method of the server.

Python
class Server:    def handle(self, request):        return f"done {request}"class LoggingMixin:    def handle(self, request):        print("log", request)        return super().handle(request)            # the next class in the orderclass LoggedServer(LoggingMixin, Server):         # mixin first    passclass WrongOrder(Server, LoggingMixin):           # Server.handle is found first    passprint(LoggedServer().handle("a"))                 # log a, done aprint(WrongOrder().handle("b"))                   # done b, and no log
The same two parents in two orders. The wrong one gives no error and no log.
Edit and run it in your browser

Rule 2

Construction needs an agreement

Every parent wants its arguments. Nobody knows who comes next in the line. The agreement that works: keyword arguments only, take your own, pass the rest on, always call super().__init__.

Python
class Person:    def __init__(self, name):        self.name = nameclass Student(Person):    def __init__(self, name, school):        super().__init__(name)                # next in the order, not always Person        self.school = schoolclass Employee(Person):    def __init__(self, name, company):        super().__init__(name)        self.company = companyclass WorkingStudent(Student, Employee):    def __init__(self, name, school, company):        super().__init__(name, school)        self.company = companytry:    WorkingStudent("Noor", "Harbour College", "Blue Cafe")except TypeError as e:    print(e)        # Employee.__init__() missing 1 required positional argument: 'company'
Without the agreement. The code looks right and fails as soon as two parents meet.
Edit and run it in your browser

Arguments on their way down the line

If something is left for object, it raises TypeError. That is good: a misspelled argument is found at once.

Rule 3

A clash must be decided, not ignored

The two parentsExampleWhat to do
Same promise, same meaningdescribe() of Student and EmployeeCooperate: each does its share and calls super()
Same promise, two answersTwo defaults of greet()Override in the join and choose
Same word, two promisesstart() of a printer and of a scannerTwo names, or two objects. Never one method
Same field name by chance_lock in two mixinsPrivate names: __lock in Python, private in C++
Row 3 is the dangerous one. Every answer in one method is wrong for one of the callers.

Judgement

Should this be a second parent?

Four questions

An order service class should log, retry and cache. Three parents?

BreaksThree full parents with state
How
class OrderService(Logger, Retrier, Cache).
Limit
A service is not a cache. get of Cache and get of the service clash, and the order of retry and cache is hidden in the header.
Choose when
Never.
WorksCooperative mixins
How
class S(LogMixin, RetryMixin, OrderService) where each wraps fetch and calls super().
Limit
Fixed per class, order matters, hard to test one alone.
Choose when
Framework code with a stable set of hooks.
StrongWrappers
How
Decorator objects around one contract: Logged(Retried(Cached(service))).
Limit
A little wiring, and the self problem.
Choose when
The set of extras differs by place or time. See Decorator.

Four safe uses

  • Many interfaces

    Abstract classes without fields. The C++ Core Guidelines recommend this use first (C.135).

  • Mixins

    Small, without a life of their own, calling super(). More in Mixins and traits.

  • Type plus value

    class Status(str, Enum): an enum whose members are also strings.

  • One main class plus helpers

    One parent says what it is, the others add finished steps.

Summary

The whole topic in one minute.

Many types are harmless, many behaviours need an order, many states need a plan. Ask which of the three you are about to inherit.

Parents that cooperate take keyword arguments, keep what is theirs, pass the rest on and always call super(). One parent that does not call it cuts the line.

When two parents use one name for two promises, or when a side can end during life, hold objects instead of extending classes.

  • Type, behaviour, state: most trouble comes from state.
  • super() is the next class in the line of the object, not the parent you think of.
  • Keyword arguments, take yours, pass the rest, always call super.
  • Mixins stand on the left.
  • One word with two promises needs two names or two objects.
  • If a side can end, it is a role to hold, not a parent.

Sources