DevPrep

All topics › Object-oriented programming (OOP)

Multiple inheritance and interfaces

Middle

Essence

Multiple inheritance is when a class inherits implementation from several parents (C++, Python). The main problem is the diamond problem: D inherits B and C, both inherit A and override the same method; which version does D get, and how many copies of A's state does it hold? Because of this ambiguity and fragility, most languages forbid multiple class inheritance.

How languages solve it

The diamond in Swift and how it is resolved

protocol Flying { func move() -> String }
protocol Swimming { func move() -> String }
extension Flying { func move() -> String { "fly" } }
extension Swimming { func move() -> String { "swim" } }

struct Duck: Flying, Swimming {
    // Without this the call `Duck().move()` is ambiguous: two defaults.
    func move() -> String { "fly or swim" }
}

print(Duck().move())                     // fly or swim
print((Duck() as any Flying).move())     // fly or swim: requirement overridden

If Duck does not implement move() itself, the compiler reports an ambiguity error: the conflict is resolved explicitly rather than by ordering rules as in C++ or Python (MRO).

Why protocols are safer

What the interviewer looks for

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store