Loading lessons...
Destructors
Destructors
A destructor is the mirror image of a constructor: it runs when an object is destroyed. Its job is cleaning up - freeing heap memory, closing a file, or releasing anything the object owned.
class Car {
public:
Car() { cout << "created\n"; } // constructor
~Car() { cout << "destroyed\n"; } // destructor
};
Rules
- The name is the class name with a tilde (
~) in front. - It returns nothing - not even
void. - A class has exactly one destructor, and it takes no parameters.
When does it run?
The destructor fires when the object's lifetime ends:
void func() {
Car myCar; // exists here
} // destroyed as the scope ends
- A local (stack) object is destroyed when the scope ends.
- An object created with
newis destroyed when you calldelete. - A global object dies when the program ends.
Cleaning up
If the constructor allocated memory with new, the destructor is the place to free it with delete - otherwise the memory leaks.
TL;DR
- A destructor looks like
~ClassName()with no return type. - It runs automatically when the object is destroyed.
- Stack objects run it at scope end; heap objects run it at
delete. - Use it to release resources the object owns.