coder coder - 11 months ago 65
C++ Question

Multiple Inheritance :Java vs C++

Recently ,after reading some articles in Programming Languages and Practice book ,it is mentioned that multiple interface inheritance in Java does not suffer from the same problems as multiple class inheritance in C++.

But I can't understand why this happens. How java is able to use multiple interface inheritance while in C++ implementation errors exists???

Is there a way to replace multiple inheritance in c++ as to avoid implementation problems???

For the last statement to be more specific ,lets sat that we have:

class A {...};
class B : public A {...};
class C : public A {...};
class D : public B, public C {...};

Then class D inherits class B,C which both inherit class A. So if A had a field-variable then B,C would have the same variable name ,then what variable would D has (inherited from B or C) .To avoid this could we write the above code without multiple inheritance but with similar results?

The question I think is not a duplicate since it is not focused on what finally will be the inheritance in the example ,but to understand the difference between Java-C++ multiple inheritance(see the first question above) and also if there is a way suggested to overcome some multiple inheritance problems (like the above).

Answer Source

Java (unlike C++) does not allow multiple inheritance of state and, therefore, does not suffer from a diamond problem.

It allows multiple inheritance of type through interfaces (a class can implement multiple interfaces).

Starting with Java 8 there is also multiple inheritance of behavior through default methods in interfaces.