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

See it run

Two paths to one ancestor: which method, and how many copies?

Operations

Which greet?

Both branches override, and the join says nothing.

Step 1 of 6

One ancestor

Animalshared ancestorgreetyesFlyingbranchgreetoverridesWalkingbranchgreetoverridesBatjoingreetnone

Animal can greet.

Step 1: One ancestor

class Animal:    def greet(self): return "Animal"class Flying(Animal):    def greet(self): return "Flying"class Walking(Animal):    def greet(self): return "Walking"class Bat(Flying, Walking):    def greet(self): return "Bat"      # the decision
Good for
Finding the ambiguity
Costs
One override to end it

Write the override, even where the language would pick for you.

In the real world

The same diamond problem doing real jobs. Pick one and step through it.

Two questions, four answers.

Step 1 of 4

C++

Which greet?How many energies?
C++errortwo, or one if virtual
Python
Java
JavaScript

Ambiguous, and two copies. virtual makes it one copy.

Step 1: C++

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • virtual in the join

    critical

    Sharing is decided where the branches name the ancestor.

    Wrong
    struct Flying : Animal {};struct Bat : virtual Flying, virtual Walking {};
    Right
    struct Flying : virtual Animal {};struct Walking : virtual Animal {};
  • Expecting virtual to choose

    major

    It removes the copy. Two overrides are still two.

    Wrong
    struct Bat : Flying, Walking {};   // greet?
    Right
    struct Bat : Flying, Walking { string greet() override; };
  • Parents by name

    critical

    The ancestor runs once per path, or a sibling is skipped.

    Wrong
    Savings.__init__(self); Shared.__init__(self)
    Right
    super().__init__()
  • Order without a test

    major

    A swap in the header changes behaviour and nobody sees it.

    Wrong
    class Bat(Walking, Flying): pass
    Right
    assert [c.__name__ for c in Bat.__mro__][:2] == ["Bat", "Flying"]
  • State in a branch

    major

    The second copy comes back by hand.

    Wrong
    class Flying(Animal):    def __init__(self): self.energy = 10
    Right
    self.spend(3)      # Animal owns energy

Interview tips

  • Two questions

    • Which method?
    • How many copies?
    • Answer both aloud
  • Two tests

    • Energy is 6
    • The order is written down
    • Ancestor set up once
  • Know the line

    • C++: virtual in branches
    • Python: super everywhere
    • Java: override
  • Or avoid it

    • Parts instead of branches
    • Interfaces without state
    • A list of steps