What is a destructor? | C++ Advanced | Part -3

What is a destructor

Destructor, a pretty animated name.

Sounds like a villain?

It actually is a life-saver when creating big projects.

A destructor is a function which destructs or deletes an object.

A destructor is called when an object of the class goes out of scope.

The name of the destructor is same as the name of the class.

But, what is the purpose of a destructor?

An object during its lifetime uses many resources and occupies memory. Right?

So the destructor function ensures that the memory and resources are free as soon as the object goes out of scope.

There cannot be more than one destructors for a class.

Remember what happens when we don’t define a constructor?

In the same way, if a destructor is not manually declared, the C++ compiler does that part.

And it is known as a default destructor. You guessed it right!

*A destructor is called when an object of the class goes out of the scope.

Using destructor in C++

Let’s see how we can write a destructor.

We already know that a destructor has the same name as the class.

The destructor function is always preceded by a tilde (~).

class Heydestructor{

public:

string name;

Heydestructor(string n){

name = n;

cout<<“Hi “<<name;

}

~Heydestructor();

};

Awesome, we have successfully written a destructor Heydestructor() for our class Heydestructor.

Let’s create an object of type Heydestructor and add some text in the destructor body.

class Heydestructor{

public:

string name;

Heydestructor(string n){

name = n;

cout<<“Hi “<<name<<“\n“;

}

~Heydestructor(){

cout<<“The object was deleted.“;

}

};

int main() {

Heydestructor hi(“Rahul“);

}

Can you try to guess the output of the above snippet?

We have created an object of type Heydestructor.

When the previous snippet is executed, we get the output.

Hi Rahul The object was deleted.

The destructor function is executed after the program senses the work of object is done.

Parameterized destructor?

Parameterized destructor does not exist.

A destructor does not take any parameters and also does not have any return type.

To summarize

  • A destructor is a function which destructs or deletes an object.
  • A destructor is called when an object of the class goes out of scope.
  • The name of the destructor is same as the name of the class.
  • The destructor function ensures that the memory and resources are free as soon as the object goes out of scope.
  • The destructor function is always preceded by a tilde (~).
  • A destructor does not take any parameters and also does not have any return type.
  • A destructor is always preceded by a tilde(~). 
  • The purpose of a destructor is to release memory and resources when the object goes out of scope.

Leave a Reply

Your email address will not be published. Required fields are marked *