What is a destructor in C++?

A destructor is called automatically when an object goes out of scope or is deleted. It has no parameters and no return type. Use it to free what the object owns (memory, files, locks).

#include <iostream>

class File {
public:
    File()  { std::cout << "open\n"; }
    ~File() { std::cout << "close\n"; }
};

int main() {
    File a;
    {
        File b;
        std::cout << "inside block\n";
    }
    std::cout << "end of main\n";
}
Output

open
open
inside block
close
end of main
close

Objects are destroyed in the reverse order of their creation. See Constructors and Destructors.


Learn more about the similar topics:
Tutorials
C++ Classes and Objects
C++ Constructors and Destructors
C++ Access Specifiers and Encapsulation
C++ Inheritance
C++ Polymorphism and Virtual Functions
C++ Abstract Classes and Interfaces
C++ Operator Overloading
Exercises & Assignments
Build a BankAccount class
Calculate areas with polymorphism
Overload operators for a Money class
Interview Questions & Answers
What is the difference between struct and class in C++?
What is a constructor in C++ and what are its types?
What is a destructor in C++?
What is the difference between overloading and overriding in C++?
What is a virtual function in C++?
What is a pure virtual function and an abstract class in C++?
What is the static keyword in C++?