C++ Language



Admission Enquiry Form

  

Destructor in C++:




What is Destructor?

A destructor is also a special function in C++ class like constructor.It's name same as the class name.But it is prefixed with a tilde sign (~).It does not have any return type.

It is used to delete or destructs the objects of classes.

It is defined only once in a class.They are called automatically when the class object goes out of scope such as when the function ends, the program ends etc.

Destructors are different from normal member functions as they don't take any argument and don't return anything.




Code for Destructor in C++.

#include <iostream>
using namespace std;
class Student
{
public:
Student()
{
cout<<"Default Constructor Invoked"<<endl;
}
~Student()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Student st1; //creating an object of Student class
Student st2; //creating an object of Student class
return 0;
}

Output:

Default Constructor Invoked
Default Constructor Invoked
Destructor Invoked
Destructor Invoked