This documentation is archived and is not being maintained.

Order of Destruction

When an object goes out of scope or is deleted, the sequence of events in its complete destruction is as follows:

  1. The class's destructor is called, and the body of the destructor function is executed.

  2. Destructors for nonstatic member objects are called in the reverse order in which they appear in the class declaration. The optional member initialization list used in construction of these members does not affect the order of (construction or) destruction. (For more information about initializing members, see Initializing Bases and Members.)

  3. Destructors for nonvirtual base classes are called in the reverse order of declaration.

  4. Destructors for virtual base classes are called in the reverse order of declaration.

// order_of_destruction.cpp
#include <stdio.h>

struct A1      { virtual ~A1() { printf("A1 dtor\n"); } };
struct A2 : A1 { virtual ~A2() { printf("A2 dtor\n"); } };
struct A3 : A2 { virtual ~A3() { printf("A3 dtor\n"); } };

struct B1      { ~B1() { printf("B1 dtor\n"); } };
struct B2 : B1 { ~B2() { printf("B2 dtor\n"); } };
struct B3 : B2 { ~B3() { printf("B3 dtor\n"); } };

int main() {
   A1 * a = new A3;
   delete a;

   B1 * b = new B3;
   delete b;

   B3 * b2 = new B3;
   delete b2;


A3 dtor
A2 dtor
A1 dtor

B1 dtor

B3 dtor
B2 dtor
B1 dtor