Sobes.tech
Middle

In what order are objects constructed and destroyed in C++?

sobes.tech AI

Answer from AI

  1. Static and global objects: constructed before the call to main(), destroyed after the completion of main().
  2. Class member objects: constructed in the order of their declaration in the class, destroyed in the reverse order when the class object is destroyed.
  3. Base classes: constructed before the derived class in the order they are listed in the initialization list, destroyed after the derived class in the reverse order.
  4. Local automatic objects (on the stack): constructed upon entering their scope, destroyed upon exiting in the reverse order of construction.
  5. Dynamically allocated objects (on the heap): constructed when new is called, destroyed when delete is called. The order is determined by the order of new and delete.

Example:

#include <iostream>

class Base {
public:
    Base() { std::cout << "Base constructed\n"; }
    ~Base() { std::cout << "Base destructed\n"; }
};

class Member {
public:
    Member() { std::cout << "Member constructed\n"; }
    ~Member() { std::cout << "Member destructed\n"; }
};

class Derived : public Base {
    Member m;
public:
    Derived() { std::cout << "Derived constructed\n"; }
    ~Derived() { std::cout << "Derived destructed\n"; }
};

int main() {
    std::cout << "Entering main\n";
    {
        Derived d; // Construction: Base -> Member -> Derived
    } // Destruction: Derived -> Member -> Base
    std::cout << "Exiting main\n";
    return 0;
}

The program output will be:

Entering main
Base constructed
Member constructed
Derived constructed
Derived destructed
Member destructed
Base destructed
Exiting main