0
0
CppConceptBeginner · 3 min read

Destructor in C++: What It Is and How It Works

In C++, a destructor is a special member function that automatically runs when an object is destroyed. It cleans up resources like memory or files that the object used during its life.
⚙️

How It Works

Think of a destructor as the cleanup crew for an object. When you create an object, it might use resources like memory or open files. The destructor is called automatically when the object is no longer needed, such as when it goes out of scope or is deleted, to release those resources.

This process helps prevent problems like memory leaks, where memory stays used even though the program no longer needs it. The destructor has the same name as the class but starts with a tilde ~, and it does not take any parameters or return anything.

💻

Example

This example shows a class with a destructor that prints a message when an object is destroyed.

cpp
#include <iostream>

class Box {
public:
    Box() {
        std::cout << "Box created\n";
    }
    ~Box() {
        std::cout << "Box destroyed\n";
    }
};

int main() {
    {
        Box b;
    } // b goes out of scope here, destructor runs
    std::cout << "End of main\n";
    return 0;
}
Output
Box created Box destroyed End of main
🎯

When to Use

Use destructors when your class manages resources that need explicit cleanup, such as dynamic memory, open files, or network connections. For example, if your class allocates memory with new, the destructor should free it with delete to avoid memory leaks.

Destructors are essential in real-world programs to keep resource use efficient and prevent crashes or slowdowns caused by resource leaks.

Key Points

  • A destructor has the same name as the class, preceded by a tilde ~.
  • It runs automatically when an object is destroyed.
  • It has no parameters and no return type.
  • It is used to free resources like memory or files.
  • Helps prevent resource leaks and keeps programs stable.

Key Takeaways

A destructor automatically cleans up when an object is destroyed.
It is named with a tilde (~) followed by the class name and has no parameters.
Use destructors to free resources like memory or files your object uses.
Destructors help prevent memory leaks and keep programs efficient.