In a C++ Programming, Destructor is also a special member like constructor.
Like a constructor, destructor have the same name as their class , preceded by a tilde(~).
Destructor does not have a return type means it cant return any value.
Destructor destroys the class object created by constructor.
It is automatically called when object goes out of scope.
Destructor releases memory space occupied by objects.
In C++ Destructor is only one way to destroy the object .
In C++ program we can define only one destructor.
Characteristics of Destructor:
- Destructor has a same name as the class in which it is resides, preceded by a tilde (~).
- Destructor is automatically called when object goes out of scope.
- Destructor is only one way to destroy the object.
- Destructor neither requires any argument nor returns any value.
- It is not possible to define more than one destructor.
- Destructor cannot be overloaded.
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> using namespace std; class A { public: A() // constructor “A” define { cout << "Constructor executed" << endl; } ~A() // Destructor “A” { cout << "Destructor executed"; } }; int main() { A obj; //object declared } |
Output
1 2 | Constructor executed Destructor executed |
Note: In the above program, class “A” contains constructor and destructor.
When object obj is created , constructor is executed. When object goes out of scope, destructor is executed.
Example: Write a C++ program to create an multiple object and releases them using destructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; class A { public: A() // constructor { cout << " Cnstructor executed " << endl; }~A() // Destructor { cout << " Destructor executed " << endl; } }; int main() { cout << " Inside main " << endl; A obj1, obj2; { cout << " Inside scope " << endl; A obj3; } cout << " Again in main " << endl; } |
Output
1 2 3 4 5 6 7 8 9 | Inside main Cnstructor executed Cnstructor executed Inside scope Cnstructor executed Destructor executed Again in main Destructor executed Destructor executed |