Destructors in C++: Object Cleanup, Rules, and Execution Timing
What is Destructors in C++: Object Cleanup, Rules, and Execution Timing? A destructor is a special member function (~ClassName) invoked automatically when an object goes out of scope or is deleted. It releases acquired resources (mem...
What is a destructor in C++, when is it called, and why must base class destructors be virtual?
Explanation & In-Depth Details
- Construction order: Base class constructor -> Member objects -> Derived class constructor.
- Destruction order: EXACT REVERSE. Derived class destructor -> Member objects -> Base class destructor.
```text
DESTRUCTION TIMELINE:
┌─────────────────────────────────────────────────────────────┐
│ 1. Derived Class Destructor body executes │
│ 2. Derived Class Member variables destroyed in reverse order│
│ 3. Base Class Destructor body executes │
│ 4. Base Class Member variables destroyed │
└─────────────────────────────────────────────────────────────┘
```
2. Virtual Destructor Requirement:
Deleting a derived object via a base pointer with a non-virtual destructor causes Undefined Behavior and memory leaks because the derived cleanup code is skipped.
Code Example
#include <iostream>
#include <memory>
class BaseResource {
public:
BaseResource() { std::cout << "BaseResource acquired.\n"; }
virtual ~BaseResource() { std::cout << "BaseResource released.\n"; }
};
class DerivedResource : public BaseResource {
private:
int* rawBuffer;
public:
DerivedResource() : rawBuffer(new int[100]) {
std::cout << "DerivedResource buffer allocated (400 bytes).\n";
}
~DerivedResource() override {
delete[] rawBuffer;
std::cout << "DerivedResource buffer deleted safely.\n";
}
};
int main() {
std::cout << "--- Polymorphic Deletion Demo ---\n";
{
std::unique_ptr<BaseResource> ptr = std::make_unique<DerivedResource>();
// Exiting scope triggers virtual destructor chain: Derived -> Base
}
std::cout << "--- Scope exited cleanly ---\n";
return 0;
}Interview Question & Tips
A: No, a destructor cannot take arguments, cannot return any value, and cannot be overloaded. There is only one destructor per class.
Q: What happens if an exception escapes from a destructor during stack unwinding?
A: The C++ runtime immediately invokes std::terminate(), abruptly ending the application. Destructors are implicitly `noexcept` since C++11 and must never allow exceptions to escape.
Best Practices
• Follow the Rule of Zero: let RAII member wrappers (smart pointers, vectors) manage cleanup automatically.
• Declare base class destructors either `public virtual` or `protected non-virtual`.
This study reference for Destructors in C++: Object Cleanup, Rules, and Execution Timing is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: