Diamond problem
hard 50 minTwo parents share one ancestor, and a child has both parents.
Video lesson · Chapter 1 of 6
Make a prediction
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
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++ | error | two, 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
criticalSharing is decided where the branches name the ancestor.
Wrongstruct Flying : Animal {};struct Bat : virtual Flying, virtual Walking {};Rightstruct Flying : virtual Animal {};struct Walking : virtual Animal {};Expecting virtual to choose
majorIt removes the copy. Two overrides are still two.
Wrongstruct Bat : Flying, Walking {}; // greet?Rightstruct Bat : Flying, Walking { string greet() override; };Parents by name
criticalThe ancestor runs once per path, or a sibling is skipped.
WrongSavings.__init__(self); Shared.__init__(self)Rightsuper().__init__()Order without a test
majorA swap in the header changes behaviour and nobody sees it.
Wrongclass Bat(Walking, Flying): passRightassert [c.__name__ for c in Bat.__mro__][:2] == ["Bat", "Flying"]State in a branch
majorThe second copy comes back by hand.
Wrongclass Flying(Animal): def __init__(self): self.energy = 10Rightself.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