Destructors in C++

Destructors in C++ with Examples

In this article, I am going to discuss Destructors in C++ with Examples. Please read our previous article where we discussed Namespaces in C++ with Examples. A destructor in C++ is a member function that works just opposite to a constructor, unlike constructors which is used for initializing an object, the destructor functions are used to destroy (or delete) the object.

What is a Destructor in C++?

A destructor in C++ is also a member function like a constructor which is also invoked automatically when the object goes out of scope or we can also explicitly call the destructor to destroy the object by making a call to delete. A destructor has the same name as the class name as a constructor, but to differentiate between them the destructor function is preceded by a tilde (~) symbol. For example, the destructor for class Test is declared: ~Test().

Example to Understand Destructors in C++

We’re all familiar with the Constructors in C++. Now let us learn about the destructor. So, for understanding Destructors C++, we have taken the following example as shown in the below image.

Example to Understand Destructors in C++

Here we have created a class called Test. Inside this Test class, we have one constructor which will print “Test Object Created” when called. We know very well that this constructor will be called whenever we create the object of class Test. Apart from other functions, we can write one more function that is the same as the class name just like a constructor but here before the function name, a tilde is used “~”. This tilde resembles this function as a destructor. So, when the destructor will execute, “Test Object Destroyed” will be printed on the screen. 

When the Destructor function will be Called in C++?

We know when the object is created the constructor function is called. Now the question is when this destructor function will be called? This destructor function will be called when the object will be destroyed. We know once the main function ends, automatically all the objects that are associated with the program get destroyed. So, the constructor is called when the object is created and the destructor is called when the object is destroyed.

Instead of creating an object like Test t; we are creating an object with the help of a pointer or we are creating the object dynamically. For a better understanding, please have a look at the below code.

When the Destructor function will be Called in C++?

As you can see in the above example, we have written delete obj. So, when we are creating an object by writing a new Test, the constructor will be called. And when we delete that object by writing delete obj then destructor will be called. The complete example code is given below.

#include <iostream>
using namespace std;
class Test
{
    public:
    Test()
    {
        cout << "Test Object Created" << endl;
    }
    ~Test()
    {
        cout << "Test Object Destroyed" << endl;
    }
};

int main()
{
    Test *obj = new Test();
    delete obj;
    return 0;
}
Output:

When the Destructor function will be Called in C++?

If an object is created dynamically then it should also be deleted when not required. So, when we say delete, the destructor function will be called. Now let us see what is the use of destructor.

Is it Mandatory to Define a Destructor in C++?

No, it is not mandatory to define a destructor in C++. If as a programmer we do not define a destructor, the compiler will provide a default one automatically. And for many classes, this compiler-provided default destructor is sufficient. We only need to define a destructor explicitly in our class when the class handles external resources that need to be released, or pointers that own the memory they point to.

What is the use of Destructor in C++?

The constructor is used for initialization purposes. It is also used for allocating resources. Then what is the use of a Destructor in C++? It is used for deallocating resources or releasing resources. We don’t have to de-initialize, we have to deallocate the resources. Which type of resources? External things. When you are acquiring any external things like heap memory, file, network connection, etc. these are all external sources. If your class acquires any of them then it should release. So, we are writing some syntax to show you what can be done in the constructor and destructor. Let us take an example class.

#include<iostream>
#include <fstream>
using namespace std;
class Test
{
    int *p;
    ifstream fis;

    Test ()
    {
        p = new int[10];
        fis.open ("my.txt");
    }
    ~Test ()
    {
        delete[]p;
        fis.close ();
    }
};

Here we have a class called Test. Inside this Test class, we have a pointer p. We have allocated this p dynamically inside the constructor. Then inside the destructor, we must delete the allocated memory otherwise this will cause memory leak problems. 

If we have to open a file input stream i.e. fis, then inside the constructor, we have to write fis.open(“my.txt”) that will open the file “my.txt”. Then inside the destructor, we must close the file as fls.close(). Don’t try to execute the above example. In our coming articles, I will explain to you File Handling in detail with Examples using C++ Language.

So, you can see it in the code. Inside the constructor, memory is allocated and the file was open and inside the destructor, memory should be deallocated and the file should be closed. So, this is an example where you can see that constructor is used for acquiring resources and the destructor is used for releasing the resources. 

Can we overload the constructor? Can we have multiple constructors? Yes. Can we have multiple destructors? No. Can the constructor or destructor return anything? No. All the rules of constructors are followed on destructor except destructor cannot be overloaded. A destructor can be virtual also.

Example to Understand Static Allocation of an object in C++:
#include <iostream>
using namespace std;

class Test
{
    public:
    Test ()
    {
        cout << "Test Created" << endl;
    }
    ~Test ()
    {
        cout << "Test Destroyed" << endl;
    }
};

void fun()
{
    Test t;
}

int main()
{
    fun();
}
Output:

Example to Understand Static Allocation of an object in C++

Example to Understand Dynamic Allocation of Object in C++:
#include <iostream>
using namespace std;

class Test
{
    int *p;
    public:
    Test ()
    {
        p = new int[10];
        cout << "Test Created" << endl;
    }
    ~Test ()
    {
        delete[]p;
        cout << "Test Destroyed" << endl;
    }
};

void fun()
{
    Test *t = new Test ();
    delete t;
}

int main()
{
   fun();
}
Output:

Example to Understand Dynamic Allocation of Object in C++

Rules to be Followed While Declaring Destructors in C++:

Destructors are special functions like constructors with the same name as the class name but preceded by a tilde (~) symbol in C++. We need to follow the below rules while working with destructors in C++:

  1. C++ Destructors do not accept arguments.
  2. You cannot return value from a destructor even if a void is not allowed. So, the destructor should not have any return type.
  3. Destructors in C++ cannot be declared const, volatile, or static. However, destructors in C++ can be invoked for the destruction of objects which are declared as const, volatile, or static.
  4. Destructors in C++ can be declared as virtual. In the next article, we are going to discuss Virtual Destructors in C++ with Examples.
When Destructor Function Called in C++?

The Destructor Function in C++ is called when one of the following events occurs:

  1. A local (automatic) object with block scope goes out of scope.
  2. An object allocated using the new operator is explicitly deallocated using delete.
  3. The lifetime of a temporary object ends.
  4. A program ends and global or static objects exist.
  5. The destructor is explicitly called using the destructor function’s fully qualified name.

In the next article, I am going to discuss Virtual Destructor in C++ with Examples. Here, in this article, I try to explain Destructor in C++ with Examples and I hope you enjoy this Destructor in C++ with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.