I can see people asking all the time whether multiple inheritance should be included into the next version of C# or Java. C++ folks, who are fortunate enough to have this ability, say that this is like giving someone a rope to eventually hang themselves.
What’s the matter with multiple inheritance? Are there any concrete samples?
The most obvious problem is with function overriding.
Let’s say have two classes
AandB, both of which define a methoddoSomething. Now you define a third classC, which inherits from bothAandB, but you don’t override thedoSomethingmethod.When the compiler seed this code…
…which implementation of the method should it use? Without any further clarification, it’s impossible for the compiler to resolve the ambiguity.
Besides overriding, the other big problem with multiple inheritance is the layout of the physical objects in memory.
Languages like C++ and Java and C# create a fixed address-based layout for each type of object. Something like this:
When the compiler generates machine code (or bytecode), it uses those numeric offsets to access each method or field.
Multiple inheritance makes it very tricky.
If class
Cinherits from bothAandB, the compiler has to decide whether to layout the data inABorder or inBAorder.But now imagine that you’re calling methods on a
Bobject. Is it really just aB? Or is it actually aCobject being called polymorphically, through itsBinterface? Depending on the actual identity of the object, the physical layout will be different, and its impossible to know the offset of the function to invoke at the call-site.The way to handle this kind of system is to ditch the fixed-layout approach, allowing each object to be queried for its layout before attempting to invoke the functions or access its fields.
So…long story short…it’s a pain in the neck for compiler authors to support multiple inheritance. So when someone like Guido van Rossum designs python, or when Anders Hejlsberg designs c#, they know that supporting multiple inheritance is going to make the compiler implementations significantly more complex, and presumably they don’t think the benefit is worth the cost.