Destructor (C++)

A destructor is a special member function that runs automatically when an object is destroyed. It shares the class name prefixed with a tilde (~) and is used to release resources the object owns.

C++

When an object goes out of scope or is deleted, its destructor is called to clean up — for example, to free memory, close a file, or release a lock.

Destructors are central to RAII, the C++ idiom where an object's lifetime controls a resource. A class managing a resource usually pairs a constructor that acquires it with a destructor that releases it.

Syntax

~ClassName() { /* cleanup */ }

Examples

C++

#include <iostream>

class Guard {
public:
    Guard() { std::cout << "created" << std::endl; }
    ~Guard() { std::cout << "destroyed" << std::endl; }
};

int main() {
    Guard g;
    std::cout << "working" << std::endl;
    return 0;
}

Output:

created
working
destroyed

Learn it in a lesson

See also

Back to the Dictionary