Example & Tutorial understanding programming in easy ways.

What is destructor and how we make it, in C++?

What is destructor?
-A destructor is a special member function that works just opposite to constructor,
-unlike constructors that are used for initializing an object, destructors destroy (or delete) the object.
Syntax-
~class_name()
{
//body
}

When destructor get called?
Destructor is automatically called when:
-The program fincished execution.
-When a scope of the object is finished.
-When you call the delete operator.

program:

#include < iostream>

using namespace std;
class Myclass
{
public:
//Constructor
Myclass(int a,int b)
{
cout<<"This is constructor"<< endl;
}
//Destructor
~Myclass()
{
cout<<"This is destructor";
}
};
int main()
{
Myclass obj(3,4);
return 0;
}


output-

This is constructor
This is destructor




Read More →