Understanding Destructors in C++

Filed Under: C++
Destructors In C++

In this tutorial, we are going to understand the concept of destructors in C++, their uses as well as try to implement them in our code.

What are the Destructors in C++?

Theoretically, a Destructor is a member function that is used to destroy or delete an object. It can be user-defined. But if not defined, by default at the time of compilation the compiler generates an inline destructor.

A destructor is invoked automatically when the object goes out of scope or is explicitly destroyed by the delete operator.

Now let us look at the syntax of defining a destructor in C++ for a class named example:

example::~example()
{
	//destructor statements;
}

Here, as you can see, the destructor function(~example()) has the same name as that of the class it belongs to.

Note: Remember before defining a destructor in C++:

  • Destructor name and class name must be same
  • A destructor name should have a tilde(‘~’) before it. For eg. ~example(){}
  • They must not accept any arguments or return anything to the function call
  • A destructor can be virtual
  • Derived classes do not inherit the destructor of their base class
  • There can only one destructor in a single class.

C++ Destructors Example

Now let us take a look at an example where we try to define our destructor for our demo class.

#include<iostream>
using namespace std;

class demo
{
	public:
		int a=10;
		
		demo() //constructor
		{
			cout<<"Constructor of demo here!"<<endl;
		}
		
		~demo() //destructor
		{
			cout<<"Destructor of demo here!"<<endl;
		}
		
		void print_demo() //function
		{
			cout<<"printed demo"<<endl;
		}
};

int main()
{
	demo demo_obj;  //object of class demo created
	cout<<demo_obj.a<<endl;
	demo_obj.print_demo(); //function called
	return 0;
}  //scope of the object ends

Output:

Constructor of demo here!
10
printed demo
Destructor of demo here!

Here,

  • Inside the demo class, we have initialized and defined a variable as a=10 and a function print_demo() respectively. Further, we have also defined the corresponding constructor – demo() and destructor – ~demo().
  • Inside the main() function we create an object demo_obj that belongs to the above demo class. This leads to the call for the constructor demo().
  • Then we also have performed some operations on it like calling the print_demo() function for the object.
  • As soon as the main() function ends, the compiler calls the destructor for the object demo_obj. Which is clear from the above output.

Explicitly Calling Destructors in C++

Apart from the fact that the compiler calls the default or user-defined destructor as soon as an object gets out of scope. The C++ programming language also allows the user to call the destructor for an object explicitly.

Let us try to call the destructor ~demo() for our previous example code. We just modify our code inside main().

#include<iostream>
using namespace std;

class demo
{
	public:
		int a=10;
		
		demo() //constructor
		{
			cout<<"Constructor of demo here!"<<endl;
		}
		
		~demo() //destructor
		{
			cout<<"Destructor of demo here!"<<endl;
		}
		
		void print_demo() //function
		{
			cout<<"printed demo"<<endl;
		}
};

int main()
{
    demo obj;
    obj.print_demo();
    obj.~demo();
    return 0;
}

Output:

Constructor of demo here!
printed demo
Destructor of demo here!
Destructor of demo here!

As you can see, as we create an object the constructor demo() is called.

After that, we explicitly call the destructor ~demo() for the object obj. This explains the 3rd line of the output ‘Destructor of demo here!’.

But, the next line is the result of the default calling of the destructor by the compiler at the end of the main() function(since the scope of the object ends).

Note: In case of local variables (the above one) calling the destructor explicitly is not recommended since the destructor will get called again at the close ‘}’ of the block in which the local was created.

Virtual Destructors in C++

Destructors in C++ can also be made virtual. They are useful when we try to delete an instance of a derived class through a pointer to base class.

Now let us look at an example to have a better understanding.

Virtual Destructor Example

#include<iostream>
using namespace std;

class Base 
{
	public:
		
		Base()
		{
			cout<<"Base Constructor"<<endl;
		}
 	   virtual ~Base()
		{
			cout<<"Base Destructor"<<endl;
		}
};

class Derived: public Base 
{
	public:
		Derived()
		{
			cout<<"Derived Constructor"<<endl;
		}
		~Derived()
		{
			cout<<"Derived Destructor"<<endl;
		}
};
int main()
{
	Base * b = new Derived;
	delete b;
}

Output:

Base Constructor
Derived Constructor
Derived Destructor
Base Destructor

Notice, this time we have used the virtual keyword before the base destructor.

It is clear from the output that inside the main() function, the instruction Base *b = new Derived leads to the call for constructors Base() and Derived() respectively.

While deleting the object b, since this time a virtual destructor is inside the base class, hence first the Derived class’s destructor is called and then the Base class’s destructor is called.

Note: if the base class destructor is not virtual then, only the base class object will get deleted(since the pointer is of a base class). This would lead to memory leak for the derived object.

Why Destructors?

Destructors deallocate memory assigned or allocated to different objects in a program as soon as they go out of scope or are explicitly deleted. If it were not for destructors, then the user would have to individually free memory space allocated to different variables or objects. Which is a pretty hectic task.

This automatic de-allocation of memory not only creates a more user-friendly environment to work but also helps manage memory efficiently.

Conclusion

Thus through this tutorial, we learned about destructors in C++. We also understood the working and use by implementing it in our code.

For any questions related to this topic, feel free to use the comments below.

References

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages