Similar to constructors which get automatically called to construct the object, destructor are special member functions which get invoked automatically before the object is being destroyed.
There are following rules of defining a destructor in the class:
- Destructor has same name as class prefixed with a tilda (
~). - Destructor does not accept any arguments.
- Destructor does not return anything.
- A class can only have one destructor.
Following shows an example of a dummy File class that opens the file in constructor and closes in destructor (just prints the logs).
#include <iostream>
class File
{
std::string m_filename{};
public:
File(std::string_view filename)
: m_filename{filename}
{
// openfile
std::cout << "Opening file: " << m_filename << "\n";
}
void read()
{
std::cout << "Reading file: " << m_filename << "\n";
}
~File()
{
std::cout << "Closing file: " << m_filename << "\n";
}
};
int main(int argc, char const *argv[])
{
File f{"./text.file"};
f.read();
return 0;
}This example shows one of the use case of destructors where it closes opened file. Other cases can be closing network connection, cleaning up stuff, etc.
Destructor with halting programs
If the program is halted using std::exit(), the program just gets end. No local variables are clean and nor any destructor gets chance to be called. Furthermore, unhandled exceptions also ends the program without unwinding the stack and due to which destructor may not be called.