Destructors for virtual base classes are called in the reverse order of their appearance in a directed acyclic graph (depth-first, left-to-right, postorder traversal). Figure 11.1 depicts an inheritance graph.
Figure 11.1 Inheritance Graph Showing Virtual Base Classes
The following lists the class heads for the classes shown in Figure 11.1.
class A
class B
class C : virtual public A, virtual public B
class D : virtual public A, virtual public B
class E : public C, public D, virtual public B
To determine the order of destruction of the virtual base classes of an object of type E
, the compiler builds a list by applying the following algorithm:
E
).
Therefore, for class E
, the order of destruction is:
E
.D
.C
.B
.A
.This process produces an ordered list of unique entries. No class name appears twice. Once the list is constructed, it is walked in reverse order, and the destructor for each of the classes in the list from the last to the first is called.
The order of construction or destruction is primarily important when constructors or destructors in one class rely on the other component being created first or persisting longer — for example, if the destructor for A
(in the graph in Figure 11.1) relied on B
still being present when its code executed, or vice versa.
Such interdependencies between classes in an inheritance graph are inherently dangerous because classes derived later can alter which is the leftmost path, thereby changing the order of construction and destruction.