AlgoViz

Multiple inheritance

hard 50 min

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

Watch lesson4:37

In each language

One design, four mechanisms.

The point: the questions are the same everywhere: one person, one name, who decides a clash. Only the mechanism changes.

QuestionPythonC++JavaTypeScript
One Person?AlwaysOnly with virtualOne parent classOne chain
Who builds it?The line of super()The last classsuper(name)super(name)
Who wins a clash?Left in the headerNobody: errorNobody: errorLast mixin applied
Seen when?At run timeAt compile timeAt compile timeType check, partly
State in the sides?YesYesNoYes, with limits for private members
C++
#include <iostream>#include <string>using std::string;struct Person {    explicit Person(string n) : name(std::move(n)) { std::cout << "Person\n"; }    string name;};struct Student : Person { using Person::Person; };struct Employee : Person { using Person::Person; };struct WorkingStudent : Student, Employee {    explicit WorkingStudent(const string& n) : Student(n), Employee(n) {}};int main() {    WorkingStudent noor("Noor");              // prints Person twice    // noor.name;                             // error: ambiguous    noor.Student::name = "Noor Khan";    std::cout << noor.Student::name << " / " << noor.Employee::name << '\n';}
C++ without virtual: two persons, two names.
Java
interface A { default String greet() { return "Hello from A"; } }interface B { default String greet() { return "Hello from B"; } }class C implements A, B {    @Override public String greet() {        return A.super.greet();          // or B.super.greet(), or your own text    }}
Java: the conflict is a compile error until the class decides. A.super is the way to one of them.
TypeScript
interface Student { school: string; study(): void; }interface Employee { company: string; work(): void; }interface WorkingStudentView extends Student, Employee { describe(): void; }class WorkingStudentAlt implements Student, Employee {  constructor(public name: string, public school: string, public company: string) {}  study(): void { console.log(this.name, "studies at", this.school); }  work(): void { console.log(this.name, "works at", this.company); }}
TypeScript: types may have many parents although classes may not.