user997112
user997112

Reputation: 30615

Destructor ordering in inheritance hierarchy

If I have the following hierarchy:

If the destructor for object of type Class F is called, the following happen in the below order:

  1. Class F (the most derived) destructor is called and finishes
  2. Class D (member object 2) destructor is called and finishes
  3. Class E (member object 1) destructor is called and finishes
  4. Class C (base of F) destructor is called and finishes
  5. Class A (base of B, which is base of C) destructor is called and finishes
  6. Class B (virtual, base of C) destructor is called and finishes

is this correct? So basically towards the end C inherits virtual B and virtual B inherits A, but C gets destroyed, then A, then virtual B?

EDIT: C++ FAQs says:

"Virtual base classes are special- their destructors are called at the end of the most derived class's constructor"

which is what I am trying to understand?

Upvotes: 2

Views: 4585

Answers (2)

anatolyg
anatolyg

Reputation: 28251

Maybe it's easiest to express the order of destructor calls as an algorithm.

Destroy

  1. Do whatever the programmer wrote in the destructor's body: F::~F() { do_this; do_that; }
  2. Destroy (call destructors for) members
  3. Destroy (call destructors for) non-virtual base classes
  4. Destroy (call destructors for) virtual base classes

This algorithm is performed by the language (or compiler), so the programmer can control only the first step.

Note: each of the further steps is recursive.

The order of destructor calls is the reverse order of constructor calls (it's good to know because the construction order is intuitive). The order of destruction of virtual bases is specified as

depth-first left-to-right traversal of the graph of base classes

Fortunately, you don't need this because you only have one.

Upvotes: 4

wilx
wilx

Reputation: 18228

Destructors execute in reverse order of constructors. That is pretty much all you need to know.

UPDATE: It holds even for virtual bases. You just have to realize that virtual bases are constructed before any other base class.

Upvotes: 3

Related Questions