+ 1
Why Multiple Inheritance possible in C++ But Not In Java.
Why Multiple Inheritance possible in C++ But Not In Java. I know the reason because compiler get confused when there is method by same name so complier can't decide which method will be executed. So, My question is then đ "how" possible in C++ đ If C++ followed then why not Java, because Java is extended version of C++
4 Antworten
+ 5
Java is not an extended version of C++. The two work quite differently.
If the compiler gets confused in C++ because of same names, we can say explicitly which method we want:
struct A { void f () {} }
struct B { void f () {} }
struct AB : public A, public B {
void foo () {
A::f();
B::f();
}
}
Trickier is the famous "diamond problem":
struct A { int a; }
struct B : public A { }
struct C : public A { }
struct D : public B, public C {
void foo () {
cout << a;
}
}
In class D, which `a` will be printed? Are there two `a`, one for B and one for C? or do B and C share the same ancestor A?
C++ solves this problem by virtual inheritance and giving the programmer both options, you can choose which behaviour you want.
Sounds complicated? It is. Java is a very simple language, and the inheritance model is simpler too. If you need to "inherit" from multiple sources you have to use interfaces which don't have these problems but they are also less flexible.
cont.
+ 5
C++ doesn't have interfaces, because interfaces usually don't make sense in C++. (Because of structural typing but I don't want to go too deep)
Multiple inheritance is just one way to do things. Ruby has mixins for example that are great for sharing code between classes. Multiple inheritance can do the same. Interfaces too to some extent. C++ has "concepts" now since C++20 that are a bit interface-like but not really.
I guess in summary, different languages do things differently. The java philosophy is that the language should be kept simple and restrictive, because too much flexibility will lead to bad code and bugs. C++ says the programmer should be able to do whatever they want.
+ 2
Schindlabua Oh Man ! Great You are my hero đ