Search code examples
c++inheritancepolymorphismvirtual-destructor

Destructor ordering in inheritance hierarchy


If I have the following hierarchy:

  • Class F contains member objects of type (Class E and Class D, declared in that order)
  • Class F inherits the concrete class Class C
  • Class C inherits the abstract/pure virtual class Class B
  • Class B inherits the concrete class class A

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?


Solution

  • 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.