Assume classes D and E and F all inherit from base class B, and that class C inherits from D and E.
(i) How many copies of class B appear in class C?
(ii) How would using virtual inheritance change this scenario? Explain your answer.
(iii) How does Java avoid the need for multiple inheritance for many of the situations where multiple inheritance might be used in C++?
Here are some of my current ideas, but I'm an by no means an expert on C++!
(i)
If C inherits from D and E which are subclasses of B, then would D and E technically be copies of their super class? Then if C inherits from D and E that would mean there are 2 copies of B in C.
(ii)
Using virtual is somewhat similar to using Abstract in Java (i think). Now given this, it would mean that there would not be multiple copies of B in C, as the instantiation would be cascaded down to the level it is needed. I am not sure how to word my explanation but say B has a function called print() which prints "i am B" and C overrides this function put prints "i am C". If you called print() on C without virtual you end up printing "i am B", using virtual would mean that it would print "i am C".
(iii)
My idea here is that Java can use interfaces to avoid the use of multiple inheritance. You can implement multiple interfaces but you can only extend one Class. I'm not sure what else to add here, so any input or relevant resources would be helpful.
(i) and (iii) are right. In my experience anyway, most of the time in C++ when I've used multiple inheritance it's been because the bases were interfaces (a concept which doesn't have keyword support in C++, but it is a concept you can execute anyway).
The first sentence of (ii) is right, however your second sentence is talking about virtual functions, which is completely different to virtual inheritance. Virtual inheritance means that there is only one copy of B
, and the D
and E
both have that same copy as their base. There is no difference in terms of functions, but the difference comes in terms of member variables (and base classes) of B
.
If there is a function that prints out B
's member variable foo
; then in case (ii) this function always prints the same value because there is only one foo
, but in case (i) calling that function from the D
base class may print a different value to calling it from the E
base class.
The term "diamond inheritance" wraps all this up in two words that serve as a good mnemonic :)