C++ Destructors
Destructors
In the Constructors chapter, you learned that a constructor runs automatically when an object is created.
A destructor is the opposite. It is a special method that runs automatically when an object is destroyed.
To create a destructor, use the same name as the class, with a tilde ~ in front of it:
Example
class MyClass {
public:
MyClass() { // Constructor
cout << "Object created\n";
}
~MyClass() { // Destructor
cout << "Object destroyed\n";
}
};
int main() {
MyClass myObj;
cout << "Hello World!\n";
return 0;
}
The object is created when MyClass myObj; runs, and destroyed when main() ends. That is why "Object destroyed" is printed last.
Destructor Rules
- The destructor has the same name as the class, with a
~in front. - It has no return type and no parameters.
- A class can only have one destructor.
- It is automatically called when the object is destroyed. You do not call it yourself.
When Is a Destructor Called?
An object is destroyed when it goes out of scope. For example, an object that is created inside a function is destroyed when the function ends:
Example
class Car {
public:
Car() {
cout << "Car created\n";
}
~Car() {
cout << "Car destroyed\n";
}
};
void drive() {
Car myCar;
cout << "Driving...\n";
} // myCar is destroyed here
int main() {
drive();
cout << "Back home\n";
return 0;
}
myCar only lives inside drive(). So "Car destroyed" is printed when drive() ends, before "Back home".
An object that is created with new is destroyed when you use delete on it.
Why Use a Destructor?
A destructor is the place to clean up after an object. The most common job is to free memory that the object created with new.
In the new and delete chapter, you created a list of hotel guests with new, and had to remember to free it with delete[]. If the class does this in its destructor, the memory is always freed, and you cannot forget it:
Example
class Hotel {
public:
string* guests;
Hotel(int rooms) {
guests = new string[rooms]; // Get memory
cout << "Rooms ready\n";
}
~Hotel() {
delete[] guests; // Free the memory
cout << "Memory freed\n";
}
};
int main() {
Hotel myHotel(3);
myHotel.guests[0] = "Liam";
cout << "Guest: " << myHotel.guests[0] << "\n";
return 0;
}
The constructor gets the memory, and the destructor gives it back. You never call delete[] in main().