As the name indicates, a C++ destructor destroys the object of a class as soon as the scope of an object ends. It is opposite to a constructor. When an object goes out of the scope, the compiler automatically calls the destructor function.
Also, the destructor has the exact same name as the class, the difference is, it is prefixed with a tilde sign (~). And the destructor cannot have parameters nor modifiers.
The syntax for C++ destructor:
1 2 3 4 5 6 7 8 9 | class Square { public: // destructor ~Square() { // statement } }; |
let us see an example of a destructor in C++.
C++ example for the Constructor and Destructor call
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // C++ program for destructor and constructor #include <iostream> using namespace std; // class class Square { public: // constructor Square() { cout << "Constructor Invoked." << endl; } //Destructor ~Square() { cout << "Destructor Invoked." << endl; } }; int main() { // creating an objects of Square class Square sq1; Square sq2; return 0; } |
Output:
Constructor Invoked.
Constructor Invoked.
Destructor Invoked.
Destructor Invoked.