I understand the basics of C++ virtual inheritance. However, I'm confused about where exactly I need to use the virtual
keyword with a complex class hierarchy. For example, suppose I have the following classes:
A
/ \
B C
/ \ / \
D E F
\ / \ /
G H
\ /
I
If I want to ensure that none of the classes appear more than once in any of the subclasses, which base classes need to be marked virtual
? All of them? Or is it sufficient to use it only on those classes that derive directly from a class that may otherwise have multiple instances (i.e. B, C, D, E and F; and G and H (but only with the base class E, not with the base classes D and F))?
You have to specify virtual
inheritance when inheriting from any of A, B, C, and E classes (that are at the top of a diamond).
class A;
class B: virtual A;
class C: virtual A;
class D: virtual B;
class E: virtual B, virtual C;
class F: virtual C;
class G: D, virtual E;
class H: virtual E, F;
class I: G, H;