Objects are destroyed in the reverse order of their construction, last constructed, first destroyed (LIFO, like a stack). This is guaranteed by the standard and it's essential for correct resource unwinding when resources have dependencies. For example, if you construct a ClockGate and then an SpiDevice that uses that clock, reverse destruction means the SpiDevice shuts down before its clock is gated, correct by construction. If destruction happened in construction order, you'd gate the clock while the device still needed it. The same principle makes nested RAII guards unwind safely. For members of a class, they're destroyed in reverse declaration order after the destructor body runs.
C++ for Embedded · Interview question
In what order are destructors called, and why does it matter?
A strong answer
What a weak answer sounds like
You know the answer. Do you know what gets you dinged?
Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.
From the lesson
Constructors, Destructors & RAII
Tie setup to object creation and cleanup to scope exit, so you can't forget to release a lock, disable a clock, or re-enable interrupts. The defining C++ idiom for embedded.
More Constructors, Destructors & RAII questions
What is RAII and why is it especially valuable in embedded?Write an RAII guard for a critical section. Why is it better than paired enable/disable calls?Why prefer the member initializer list over assigning members in the constructor body?If a class has a destructor that releases a resource, what else must you consider?
Browse all 472 interview questions