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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.