C++

C++ - [OOP] Destruction

Destruction Ordering

Posted by Rico's Nerd Cluster on March 2, 2023

The destruction order is Derived Class -> Derived class members -> base class, which is the inverse order of construction: base class -> Derived class members -> Derived Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

struct A
{
    ~A() { std::cout << "A\n"; }
};

struct C
{
    ~C() { std::cout << "C\n"; }
};

struct B : public A
{
    C c1;                   // data-member declared *after* any implicit A sub-object

    ~B() { std::cout << "B\n"; }
};

int main()
{
    {
        B obj;              // construct a B on the stack
    }                       // scope ends → destructors run

    return 0;
}