Destructor
Similar to a constructor, a class has another special member function called destructor. Destructor cleans up the object before it is destroyed.
Similar to a constructor, destructor is also called implicitly. A destructor of a class is called
-
when an object goes out of scope.
-
when the pointer to the object is released using delete operator.
-
when the program terminates for static or global objects
-
when delete [] operator is called for array of objects.
Destructor has the same name as class and is preceded by tilde (~) symbol. And it takes no parameters. Which means a class can have only one destructor.
e.g. Class A has a destructor ~A()
Destructor should be used to clean up the object - release memory and other resources, close files, stop threads etc.
In the above code, you see the destructor of class Arr, which releases the memory allocated by constructor. The object obj is destroyed when main function terminates, and its destructor is called which releases the memory allocated for 10 integers.
The output of the program is
./a.out
in main
constructor
destructor
If there is no user defined destructor, then compiler provides a trivial destructor.
The example shown above uses dynamic memory and hence needs user defined destructor to release memory.
The members of a class which are classes can have their own destructors.
When a destructor is called, it automatically calls destructors of base classes and destructors of member objects.
Order of destructor call
Destructor of an object is called when the object is being destroyed - that is when the object goes out of scope.
-
For global objects, destructor is called at the end of the program.
-
For local objects, it is called when the block exits.
-
For parameters and return values, it is called when the function exits.
-
For dynamically created objects, destructor is called when delete operator is used.
Also note that the order of destructors is the opposite of order of constructors. Which means that the object created last, is destroyed first.
The program below shows the order of destructors.
The output of the program above will be
constructor10
constructor15
Destructor15
constructor12
Destructor12
Destructor10
As the destructor of a class takes no parameters, it can't be overloaded - a class can have only one destructor.
Note :
-
Compiler provides the following 4 functions automatically for every class
-
Default constructor - if the class has no other constructors
-
Copy Constructor
-
Destructor
-
Assignment operator
-
-
Destructor should be public. If not, objects of class can not be destroyed.
-
Destructor of a class can be virtual.