C++ Destructors
A destructor is a special method that runs when an object is destroyed. Its name is the class name with a tilde in front.
Made and removed around a scope
The Tag constructor prints when the object is made. The destructor prints when the inner scope ends, before the last line of main.
#include <iostream>
#include <string>
class Tag {
public:
std::string name;
Tag(std::string n) {
name = n;
std::cout << "Made " << name << std::endl;
}
~Tag() {
std::cout << "Removed " << name << std::endl;
}
};
int main() {
std::cout << "Start" << std::endl;
{
Tag t("A");
std::cout << "Inside" << std::endl;
}
std::cout << "End" << std::endl;
return 0;
}Reverse order of birth
The inner object is born second and dies first. The outer object is born first and dies last.
#include <iostream>
#include <string>
class Tag {
public:
std::string name;
Tag(std::string n) {
name = n;
std::cout << "Made " << name << std::endl;
}
~Tag() {
std::cout << "Removed " << name << std::endl;
}
};
int main() {
Tag outer("Outer");
{
Tag inner("Inner");
std::cout << "Both alive" << std::endl;
}
std::cout << "Outer still alive" << std::endl;
return 0;
}An object dies when a function returns
The Tag object lives inside the job function. Its destructor runs at the return, before the next line of main prints.
#include <iostream>
#include <string>
class Tag {
public:
std::string name;
Tag(std::string n) {
name = n;
std::cout << "Made " << name << std::endl;
}
~Tag() {
std::cout << "Removed " << name << std::endl;
}
};
void job() {
Tag t("Job");
std::cout << "Working" << std::endl;
}
int main() {
job();
std::cout << "Back in main" << std::endl;
return 0;
}Example
#include <iostream>
class FileGuard {
public:
FileGuard() {
std::cout << "File opened" << std::endl;
}
~FileGuard() {
std::cout << "File closed" << std::endl;
}
};
int main() {
std::cout << "Job starts" << std::endl;
{
FileGuard guard;
std::cout << "Line one written" << std::endl;
std::cout << "Line two written" << std::endl;
}
std::cout << "Job ends" << std::endl;
return 0;
}Key points
- A destructor has the same name as its class, with a ~ in front.
- A destructor takes no parameters and returns nothing.
- A destructor runs when an object goes out of scope.
- Objects are destroyed in the reverse order of their creation.
- An object made inside a function is destroyed when the function returns.
- A class has at most one destructor.
In this example, the FileGuard constructor prints File opened when the guard is made. Two lines print while the guard is alive. The scope then ends, the destructor prints File closed, and main prints its last line.
Note
A program never calls a destructor by name. The scope ends and the destructor runs on its own.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
When does a destructor run?