Destructors
beginnerA destructor is a special member function that runs automatically when an object is destroyed.
Purpose
- Free resources (memory, file handles, network connections)
- Clean up before the object is removed
Syntax
Key Properties
- Same name as class, preceded by ~
- Takes no arguments
- No return type
- Cannot be overloaded (only one per class)
- Called automatically when object goes out of scope
When Destructors Are Called
- Stack objects: When they go out of scope
- Heap objects: When delete is called
- Static objects: When the program ends
- Temporary objects: When the expression completes
Destructor Order
Destructors are called in reverse order of construction. Derived class destructor runs before base class destructor.
Key takeaway: Destructors run in reverse construction order — derived class destructor runs before base class destructor.