C++ constructor/destructor order

Last update: 27 December, 2025

The following C++ code prints when run:

Base::Base
A::A
B::B
Derived::Derived
Derived::~
B::~
A::~
Base::~

The code:

struct Base
{
    Base() { std::cout << "Base::Base" << std::endl; }
    virtual ~Base() { std::cout << "Base::~" << std::endl; }
};

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

struct B
{
    B() { std::cout << "B::B" << std::endl; }
    ~B() { std::cout << "B::~" << std::endl; }
};

struct Derived final : public Base
{
    A a;
    B b;
    Derived() { std::cout << "Derived::Derived" << std::endl; }
    ~Derived() { std::cout << "Derived::~" << std::endl; }
};

int main()
{
    Derived derived;
    return 0;
}

From C++20 standard draft:

In a non-delegating constructor, initialization proceeds in the following order: (13.1) — First, and only for the constructor of the most derived class (6.7.2), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list. (13.2) — Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers). (13.3) — Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers). (13.4) — Finally, the compound-statement of the constructor body is executed. [Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. —end note]

Other things to read

Popular

Previous/Next