logo codesdope


Destructors are functions which are just the opposite of constructors. In this chapter, we will be talking about destructors.

We all know that constructors are functions which initialize an object. On the other hand, destructors are functions which destroy the object whenever the object goes out of scope.

It has the same name as that of the class with a tilde (~) sign before it.

class A

Here, ~A() is the destructor of class A.

Destructors don't take any argument and have no return type.

When is a destructor called?

A destructor gets automatically called when the object goes out of scope. We know that a non-parameterized constructor gets automatically called when an object of the class is created. Exactly opposite to it, since a destructor is also always non-parameterized, it gets called when the object goes out of scope and destroys the object.

If the object was created with a new expression, then its destructor gets called when we apply the delete operator to a pointer to the object. We will learn more about new and delete in the chapter Dynamic Memory Allocation.

Destructors are used to free the memory acquired by an object during its scope (lifetime) so that the memory becomes available for further use.

Let's see an example of a destructor.

#include <iostream>

using namespace std;

class Rectangle
	int length;
	int breadth;
		void setDimension(int l, int b)
			length = l;
			breadth = b;
		int getArea()
			return length * breadth;
		Rectangle()              // Constructor
			cout << "Constructor" << endl;
		~Rectangle()             // Destructor
			cout << "Destructor" << endl;

int main()
	Rectangle rt;
	rt.setDimension(7, 4);
	cout << rt.getArea() << endl;
	return 0;

In this example, when the object 'rt' of class Rectangle was created, its constructor was called, no matter in what order we define it in the class. After that, its object called the functions 'setDimension' and 'getArea' and printed the area. At last, when the object went out of scope, its destructor got called.

Note that the destructor will get automatically called even if we do not explicitly define it in the class.

The difference between ordinary and extraordinary is practice.
-Vladimir Horowitz

Share what you know
Doubt? Ask question

Welcome.please sign up.


Welcome.please login.