Multiple inheritance
hard 50 minA 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.
| Question | Python | C++ | Java | TypeScript |
|---|---|---|---|---|
| One Person? | Always | Only with virtual | One parent class | One chain |
| Who builds it? | The line of super() | The last class | super(name) | super(name) |
| Who wins a clash? | Left in the header | Nobody: error | Nobody: error | Last mixin applied |
| Seen when? | At run time | At compile time | At compile time | Type check, partly |
| State in the sides? | Yes | Yes | No | Yes, 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';}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 }}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); }}