• In C++ destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed.
  • A destructor meaning is the last function that is going to be called before an object is destroyed.
  • If the object is created by using new or the constructor uses new to allocate memory which resides in the heap memory or the free store, the destructor should use delete to free the memory, the thing is to be noted here.
  • When the objects are destroyed, destructor function is automatically invoked.
  • Destructor does not have arguments and it cannot be declared as constant or static.
  • Destructor cannot become a member of the union while with an object of a class.
  • The programmer cannot access the address of destructor and in public section of class destructor should be declared.
  • If the object goes out of scope, destructor function is called automatically were the function ends, the program ends, a block containing local variables ends, a delete operator is called.
  • Destructors have same name as the class preceded by a tilde (~) it doesn’t take any argument and return anything.

Sample Code

#include<iostream>
using namespace std;
class Demo {
private:
int num1, num2;
public:
Demo(int n1, int n2) {
cout<<"Inside Constructor"<<endl;
num1 = n1;
num2 = n2;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
~Demo() {
cout<<"Inside Destructor";
}
};
int main() {
Demo obj1(30, 50);
obj1.display();
return 0;
}

Output

Categorized in: