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))?
I toyed a program together which could help you to study the intricacies of virtual bases. It prints the class hierarchy under
I
as a digraph suitable for graphiviz ( http://www.graphviz.org/ ). There's a counter for each instance which helps you to understand the construction order as well. Here's the programm:If I run this (
g++ base.cc ; ./a.out >h.dot ; dot -Tpng -o o.png h.dot ; display o.png
), I get the typical non-virtual base tree: alt text http://i34.tinypic.com/2ns6pt4.pngAdding enough virtualness...
..results in the diamond shape (look at the numbers to learn the construction order!!)
alt text http://i33.tinypic.com/xpa2l5.png
But if you make all bases virtual:
You get a diamond with a different initialization order:
alt text http://i33.tinypic.com/110dlj8.png
Have fun!