Destructor
- C++ course
- Intermediate
- Lesson 11/116
- 5 min
Learn object cleanup with the destructor.
Destructor
A destructor is a member function called automatically when an object is destroyed. A tilde (~) is placed before the class name; it has no parameters and no return type. Its purpose is to release the resources held by the object.
Example: class Logger { public: ~Logger() { std::cout << "Closed"; } };. When a Logger log; variable goes out of scope (for example, when main ends), ~Logger is called automatically and prints "Closed". Each class has at most one destructor and it takes no parameters.
Leaving scope
An object on the stack is destroyed automatically when its declaring block ends, and its destructor runs. This is the basis of a technique called RAII (Resource Acquisition Is Initialization): a resource's lifetime is tied to the object's lifetime.
Example: if you declare Logger log; inside a function, ~Logger is called when the function returns. If open files, allocated memory or open connections are closed in the destructor, the resource does not leak even if the programmer forgets. That is why modern C++ prefers stack allocation and smart pointers over new.
Practice Add a destructor to the Logger class
Define a Logger class. Under public: add a constructor that starts with Logger() { std::cout << "Open"; and a destructor ~Logger() { std::cout << "Closed"; }. In main create a Logger log; instance; the destructor is called automatically when the program ends.
Starter code
#include <iostream>
// Define the Logger class here
int main() {
// Create a Logger instance
return 0;
}Sample solution
#include <iostream>
class Logger {
public:
Logger() {
std::cout << "Open";
}
~Logger() {
std::cout << "Closed";
}
};
int main() {
Logger log;
return 0;
}Expected output
OpenClosed
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each trait to its meaning
| Term | Meaning |
|---|---|
~Logger() |
Destructor signature |
When object leaves scope |
Call moment |
Takes no parameters |
Destructor rule |
Releasing resources |
Destructor purpose |
2 How many parameters does a destructor take?
~Logger() { }- As many as you want
- At least one
- Zero, it takes no parameters Correct answer
- Only int
Explanation: A destructor takes no parameters.
3 Complete the destructor signature
class Logger { public: ____Logger() { std::cout << "Closed"; } };
class Logger { public: ~Logger() { std::cout << "Closed"; } };
Explanation: The tilde marks a destructor: ~Logger().