In C++, in what order are a class's members, its base classes and a function's local objects destroyed, and why?
answer
- mirror image of construction
- body first, then members
- declaration order, reversed
- bases after members
- partly built objects too
basics
~20 sDestruction mirrors construction: locals die in reverse order of construction, and a destructor runs its body, then destroys data members in reverse declaration order, then base classes in reverse order, so nothing outlives what it depends on.
solid answer
~50 sEverything is destroyed in the reverse order of the completion of its construction. For local objects in a block that means the last one declared is destroyed first. For a class, the destructor's body runs first, then the non-static data members are destroyed in reverse declaration order (members are always built in declaration order, whatever order the member initializer list is written in), then the direct base classes in reverse order, and virtual bases last when the object is the most derived. The reason is dependency: a later member or a derived part may use an earlier one, so it must be gone before the thing it uses. If a constructor throws partway, the class's own destructor body does not run, but every member and base that finished construction is destroyed, again in reverse order.
code
cpp · 31 lines#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
struct Trace {
std::string name;
explicit Trace(std::string n, bool fail = false) : name(std::move(n)) {
if (fail) throw std::runtime_error(name + " failed");
std::cout << " acquire " << name << '\n';
}
~Trace() { std::cout << " release " << name << '\n'; }
};
struct Base { Trace b{"base"}; };
struct Migration : Base {
Trace file; // declared first
Trace lock;
Trace txn; // declared last
explicit Migration(bool fail_txn)
: file("file"), lock("lock"), txn("txn", fail_txn) {}
~Migration() { std::cout << " ~Migration body\n"; }
};
int main() {
std::cout << "normal:\n";
{ Migration m(false); }
std::cout << "txn constructor throws:\n";
try { Migration m(true); } catch (const std::exception& e) {
std::cout << " caught: " << e.what() << '\n';
}
}go deeper
Recall that the last object constructed is the first destroyed, for locals in a block and for the members of a class.
Walk the full sequence: destructor body, then members in reverse declaration order, then bases, and explain that members follow declaration order, not the initializer list.
Use the order deliberately: declare members in dependency order, and explain how partial construction destroys only finished subobjects, which is why raw handles in a constructor body leak.
Treat member declaration order as part of a class's contract in review, because reordering members silently changes shutdown order and can turn a clean exit into a crash.
## The one rule C++ destroys objects in the **reverse order of the completion of their construction**. The standard states it for locals at scope exit, for objects destroyed by stack unwinding, and for the subobjects of a class. Learn the rule once and every case below follows from it. ## Local objects In a block, objects are constructed as their declarations are reached and destroyed when control leaves the block, last-constructed first: - `File f; Lock l; Txn t;` is destroyed as `t`, then `l`, then `f`; - the same order applies whether the block is left by falling off the end, by `return`, `break`, `continue`, `goto`, or by an exception; - an object whose declaration was never reached was never constructed and is not destroyed. ## Inside a class: body, members, bases A destructor for class `X` does its work in a fixed sequence: 1. the **destructor body** runs (and any locals declared in it are destroyed when it ends); 2. the **non-static data members** are destroyed in reverse order of declaration; 3. the **direct non-virtual base classes** are destroyed in reverse order of the base-specifier list; 4. if `X` is the most derived class, its **virtual base classes** are destroyed last. | Phase | Construction order | Destruction order | |---|---|---| | Virtual bases | first (most derived class only) | last | | Direct bases | in base-specifier order | reverse | | Data members | in declaration order | reverse declaration order | | Body | constructor body last | destructor body first | Members are constructed in **declaration order**, never in the order of the member initializer list; a compiler warns when the two disagree (clang's `-Wreorder-ctor`). The destruction order follows declaration, too, which is why reordering a member initializer list never changes it. ## Why reverse order is the right one Order encodes dependency. In a migration tool, a `Migration` object might hold a log file, then a schema lock, then an open transaction: - the transaction is opened while the lock is held, so it must be finished (rolled back) **before** the lock is released; - the lock was taken after the file was opened, so its release can still be logged; - the base class part was built first, so the derived members may use it in their destructors, and it must outlive them. Reverse order gives exactly that, provided members are **declared** in dependency order. Declaring the transaction before the lock would release the lock while the transaction is still open. ## A constructor that throws partway If the transaction's constructor throws, the `Migration` object never finished construction. The rules: - the `Migration` destructor body does **not** run, because there is no complete object; - every subobject whose construction **completed** (the base, the file, the lock) is destroyed, in reverse order; - the subobject that was being built when the exception left (the transaction) is not destroyed, because it never existed. This is why members that are themselves RAII types make a class safe by construction, while a class that acquires two raw handles in its constructor body leaks the first when the second acquisition throws. One special case: a **delegating constructor** whose target constructor has already returned owns a complete object, so if the delegating constructor's body then throws, the object's destructor is invoked. ## Temporaries and statics follow the same rule The reverse-order rule is not limited to blocks and classes: - a **temporary** is destroyed at the end of the full-expression that created it, and several temporaries from one expression are destroyed in reverse order of their creation; - objects with **static storage duration** (globals, function-local `static`s) are destroyed after `main` returns or `std::exit` is called, in the reverse order of the completion of their construction; - elements of an array are destroyed from the last element to the first. So a global logger constructed before a global connection pool outlives it at shutdown, which is the order the pool's destructor needs if it logs. ## What interviewers listen for They want the phrase "reverse order of construction", the body-members-bases sequence, and the partial-construction case. Members initialized in declaration order and the reason (dependency) mark a candidate who has debugged a shutdown crash rather than memorised a list.
- Does writing the member initializer list in a different order change the order in which members are destroyed?No. Members are initialized in the order they are declared in the class, whatever order the initializer list uses, and destroyed in the reverse of that declaration order. A mismatched list only misleads the reader, which is why clang warns with `-Wreorder-ctor`. To change destruction order, change the declaration order.
- When a C++ destructor runs, can its body still use the class's data members and base class?Yes. The destructor body runs before any member or base is destroyed, so all of them are still alive inside it. That is why a destructor can roll back a transaction using a connection member: the members go only after the body finishes, last-declared first, and the bases after them.
- If a constructor's body acquires two raw handles and the second acquisition throws, what happens to the first?It leaks. The object never finished construction, so its destructor body, where the release was written, does not run; only fully constructed subobjects are destroyed. Holding each handle in its own RAII member fixes it, because the first member's own destructor runs during unwinding.
- Members are destroyed in the order they were declared, first to last
- Members are built in the order of the member initializer list
- Base classes are destroyed before the derived class's members
- If a constructor throws, the class's destructor runs to clean up
- Destruction order of members is unspecified and up to the compiler