C++ Destructor
Destructor is used to destroy the objects created by a constructor. Name of the destructor is same as the name of class, but it preceded by a tilde(~).
Destructor neither takes any argument nor returns any value. Compiler implicitly invokes upon the destructor to exit from the program.
Syntax:
1 2 3 4 |
className(){ } |
C++ Destructor Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include<iostream> using namespace std; class Employee{ public: Employee(){ cout << "Constructor called"<<endl; } ~Employee(){ cout << "Destructor called"<<endl; } }; int main() { cout<<"Constructor Called emp1=";Employee emp1; // Constructor Called int id=101; if(id){ cout<<"Constructor Called emp2=";Employee emp2; // Constructor Called } // Destructor Called for emp2 return 0; } // Destructor called for emp1 |
Output:
1 2 3 4 5 6 |
Constructor Called emp1= Constructor called Constructor Called emp2= Constructor called Destructor called Destructor called |