The destructor is also a special member function like constructor. Destructors destroy the class objects created by constructors. The destructors have the same name as their class, preceded by a tilde (~).
For local and non-static objects, the destructor is executed when the object goes out of scope. In case the program is terminated by using return or exit() statements, the destructor is executed for every object existing at that time. It is not possible to define more than one destructor. The destructor is only one way to destroy the object. Hence, they cannot be overloaded.
A destructor neither requires any arguments nor returns any value. It is automatically called when object goes out of scope. Destructor releases memory space occupied by the objects.
The program given below explains the use of destructor.
9.13 Write a program to demonstrate execution of constructor and destructor.
Explanation: In the above program, the class text contains constructor and destructor. In function main(), object t is executed. When object t is declared, constructor is executed. When object goes out of scope, destructor is executed.
9.14 Write a program to create an object and release them using destructors.
Explanation: In the above program, the variable c is initialized with zero. The variable c is incremented in constructor and decremented in destructor. When objects are created, the compiler calls the constructor. Objects are destroyed or released when destructor is called. Thus, the value of a variable changes as the constructors and destructors are called. The value of a variable of c shows number of objects created and destroyed. In this program, the objects a and b are created in main(). The object c is created in another block, that is, in block A. The object c is created and destroyed in the same block. The objects are local to the block in which they are defined. The objects a and b are released as the control passes to main() block. The object created last is released first.