Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not recommended to use multiple inheritance?

I am creating S4 classes in R.

I read in https://github.com/hadley/devtools/wiki/S4

Note that S4 supports multiple inheritance, but this should be used with extreme caution as it makes method lookup extremely complicated.

What is method lookup and why is it more complex with multiple inheritance?

like image 492
RockScience Avatar asked Jan 12 '12 08:01

RockScience


People also ask

Why multiple inheritance is not a good idea?

Allowing multiple inheritance makes the rules about function overloads and virtual dispatch decidedly more tricky, as well as the language implementation around object layouts. These impact language designers/implementors quite a bit and raise the already high bar to get a language done, stable, and adopted.

Why multiple inheritance is not used in Java?

Java doesn't support multiple inheritances in classes because it can lead to diamond problem and rather than providing some complex way to solve it, there are better ways through which we can achieve the same result as multiple inheritances.

What are the disadvantages of multiple inheritance?

The main consequence of multiple inheritance is the diamond problem: In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C.

Is multiple inheritance evil?

It's perceived to be evil because it's just more complex and raises more issues than people typically expect, especially where base classes are not purely abstract (no data members). Diamond inheritance can be solved using virtual inheritance, where a common base is shared.


1 Answers

When you type f(x), with x belonging to several classes (say, A, B and C), the computer has to decide which f method to call (that from class A, B, or C): this is called "method lookup".

Multiple inheritance often poses problems when the code evolves.

Imagine you have written two base classes A and B, and class C inherits from both. Everything works fine. A few months later, a developer, who uses class A, and is completely unaware of classes B and C (he does not need them), adds a new method to class A. Unbeknownst to him, there is already a method with the same name in class B. What happens to objects of class C? Will the method from A or B be used? In some languages, the code may fail, in others you can have an undefined behaviour and a very hard-to-catch bug.

like image 121
Vincent Zoonekynd Avatar answered Nov 15 '22 10:11

Vincent Zoonekynd