AlgoViz

Diamond problem

hard 50 min

Two parents share one ancestor, and a child has both parents.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 5:10

Diamond problem

1:03Reel

Theory

Read or listen first. About 2 min.

What it is

Draw it and you see the name. Animal on top, Flying and Walking below, and Bat at the bottom with both as parents. Two ways lead from Bat to Animal, and the picture is a diamond.

There are two separate questions. Which method? Flying and Walking both override greet, and Bat says nothing. How many copies? Animal has a field energy. Does a bat have one or two? A language must answer both, and the answers are independent.

General rules for several parents are in Multiple inheritance. This page is about the shared ancestor only. In Python the case is always there: every class ends in object, so any two parents form a diamond.

Why it exists

Without a rule the program is ambiguous. With a silent rule it may do something nobody chose. With two copies of the state, one object holds two truths: flying uses one energy, walking uses the other, and the bat never gets tired.

Constructors are hit as well. If both parents set up the ancestor, its work is done twice: two accounts opened, two connections made.

Knowing the rule of your language turns a riddle into one line: an override, the word virtual, or a correct order of parents.

A short history

  1. 1989

    C++ 2.0 brings multiple inheritance. Virtual base classes let several paths share one ancestor.

  2. 1996

    A Monotonic Superclass Linearization for Dylan (OOPSLA, October) presents the C3 algorithm for a consistent order of parents.

  3. 2003

    Python 2.3 takes C3 for its method resolution order, after Samuele Pedroni showed in 2002 that the order of Python 2.2 was not monotonic.

  4. 2014

    Java 8 default methods make diamonds of interfaces possible. The compiler refuses the unresolved ones.

  5. 2023

    Java 21 (JEP 431) adds reversed() to List and to Deque. LinkedList implements both and had to be given its own version.

Words to know

Shared ancestor
The class at the top that can be reached by more than one path.
Ambiguity
Two candidates and no rule that prefers one.
Virtual base
C++: a base that exists once in the object, however many paths lead to it.
Most derived class
C++: the class of the whole object. Its constructor builds the virtual bases.
Dominance
C++: an override on one path beats the version of the shared virtual base.
Linearization
Turning the graph of parents into one line.
C3
The merge that Python uses: children before parents, parents in the order you wrote.
Monotonic
If A stands before B in a class's order, it does in the orders of all its children.
Most specific implementation
C# and Java interfaces: the one whose interface extends all other candidates.
Sister call
One branch calls a method that the other branch implements.

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

Find the ancestor. Can it be reached by two paths?

Understand it

Start here

One song and one money box

Four people live on a hill. Asha lives on top, Sam and Lee on the two sides, Max at the bottom. The paths between the houses form a diamond. Asha passes down a song and a money box.

The hill with four houses
LA LA10

Song: the method. Box: the state. Three answers: share the box, form a line, or decide for yourself.

Structure

Animal, flying, walking, bat

Bad: nobody decides

Animal# energy+ greet()

1/4The ancestor

One method, one field.

extends (is a)

Good: shared state, decided method

virtualvirtualAnimal# energy+ greet()# spend(n)Flying+ greet()+ fly()Walking+ greet()+ walk()

1/3One Animal

In C++ the branches name Animal as virtual. In Python this is always so.

extends (is a)

Two problems

Method and state are separate

Which method?How many copies?
C++, plainError: ambiguousTwo
C++, virtual basesError if both branches override; fine if one does (dominance)One
PythonFirst in the MROOne
Java interfacesError if both override; fine if one doesNone: interfaces have no fields
C# interfacesError: no most specific implementationNone
JavaScript mixinsLast mixin appliedOne
Scala traitsLast in the linearizationOne
EiffelShared under one name, replicated under twoAs you name it
Note the second row. virtual removes the copy, not the choice.

Four signs of a diamond

  • Ambiguous call

    The compiler says that a member was found in two base classes.

  • Setup twice

    A log line of the ancestor appears twice for one object.

  • Two values

    You set a field and read another value through the other branch.

  • A parent is skipped

    One branch does not call super(), and the other never runs.

C++
#include <iostream>#include <string>struct Animal { int energy = 10; std::string greet() const { return "Animal"; } };struct Flying : Animal { void fly() { energy -= 3; }  std::string greet() const { return "Flying"; } };struct Walking : Animal { void walk() { energy -= 1; } std::string greet() const { return "Walking"; } };struct Bat : Flying, Walking {};int main() {    Bat bat;    // bat.greet();              // error: member found in two base classes    // bat.energy;               // error: ambiguous    // Animal& a = bat;          // error: which Animal?    bat.fly();    bat.walk();    std::cout << bat.Flying::energy << ' ' << bat.Walking::energy << '\n';   // 7 9    std::cout << bat.Flying::greet() << ' ' << bat.Walking::greet() << '\n';}
C++ without virtual. Three errors that you can try, and one quiet bug: the bat has 7 and 9 energy at once.

Answer 1

Python makes a line

Python computes one order for each class and searches it from left to right. super() means the next in that order. In class Bat(Flying, Walking) the next after Flying is Walking, not Animal.

bat.greet() and bat.identify() on the line

Python
class Base:    def __init__(self, **rest):        print("Base gets", rest)        super().__init__(**rest)class Mixin1(Base):    def __init__(self, *, first, **rest):        print("Mixin1", first)        super().__init__(**rest)class Mixin2(Base):    def __init__(self, *, second, **rest):        print("Mixin2", second)        super().__init__(**rest)class Combined(Mixin1, Mixin2):    def __init__(self, **rest):        print("Combined")        super().__init__(**rest)Combined(first="M1", second="M2")# Combined, Mixin1 M1, Mixin2 M2, Base gets {}
Every class runs once, and each takes its own argument on the way.
Edit and run it in your browser

Answer 2

C++ shares the base

What is inside the object

Answer 3

Java and C# refuse

A class has one parent class, so state can never be doubled. Interfaces may form a diamond of default methods. If only one branch overrides, that one is used. If both do, the class must override. The three rules are explained in Multiple parents in single inheritance.

How the Java compiler decides

Answer 4

JavaScript has one chain

A class extends one class. A mixin is a function from class to class, so the result is a line: Bat, Flying, Walking, Animal. No diamond can form. Object.assign copies methods instead, and the last copy wins without a word.

JavaScript
const FlyingMixin = (Base) => class extends Base { fly() { return `${this.name} flies`; } };const WalkingMixin = (Base) => class extends Base { walk() { return `${this.name} walks`; } };const SwimmingMixin = (Base) => class extends Base { swim() { return `${this.name} swims`; } };class Creature {  constructor(name) { this.name = name; }  greet() { return `Hello, I am ${this.name}`; }}class Duck extends SwimmingMixin(FlyingMixin(WalkingMixin(Creature))) {  quack() { return `${this.name} says quack`; }}const duck = new Duck("Donald");console.log(duck.greet(), duck.fly(), duck.walk(), duck.swim(), duck.quack());console.log(duck instanceof Creature);            // true
Three mixins around one base.
JavaScript
const flying = {  fly() { return `${this.name} flies`; },  land() { return `${this.name} landed`; },};const walking = { walk() { return `${this.name} walks`; } };class Bird { constructor(name) { this.name = name; } }Object.assign(Bird.prototype, flying, walking);   // copies methods, the last one winsconst sparrow = new Bird("Sparrow");console.log(sparrow.fly(), sparrow.walk(), sparrow.land());
The other way: copying methods onto the prototype. There is no super in copied methods.

Judgement

Keep, share or remove the diamond?

Two branches override the same method and a class needs both branches.

BreaksLet the language pick
How
Leave the method out of the join and hope for the order.
Limit
Swapping two words in a header changes behaviour. In C++ and Java it does not compile.
Choose when
Never on purpose.
WorksOverride in the join
How
Write the method and call one or both branches by name.
Limit
If both branches call the ancestor, its work is done twice.
Choose when
The branches are independent of each other.
StrongCooperate or compose
How
Python: each branch does its share and calls super(). Elsewhere: one class with parts, see Object composition.
Limit
A cooperation rule for everybody, or forwarding lines.
Choose when
New code.

Harmless diamonds

  • The ancestor has no fields
  • Only one branch overrides
  • All branches cooperate through super()
  • The ancestor is an interface

Harmful diamonds

  • Fields in the ancestor, no sharing
  • Both branches override, nobody decides
  • Constructors with side effects
  • Branches from different owners

Summary

The whole topic in one minute.

Two questions: which method, and how many copies. C++ virtual inheritance answers the second. The first still needs an override when both branches have one.

Python puts the classes in one line (C3) and super() walks it, so the ancestor runs once. The order of parents is then part of the meaning.

Java and C# keep state out of it and ask for an override. JavaScript has one chain, so there is no diamond, only an order of mixins.

  • Two questions: which method, how many copies.
  • C++: virtual in the branches, and the last class builds the ancestor.
  • Python: one line by C3, super() is the next in it.
  • Java and C#: override, or it does not compile.
  • JavaScript: one chain, the order of mixins decides.
  • An explicit override is the clearest answer everywhere.

Sources