Destructor/ in C++

Rohan KotkarRohan Kotkar
2 min read

When an object is about to be destroyed, a member function called the destructor is automatically called. Destructors are hence the final functions to be called before an object is destroyed.

Characteristics of Destructor:

  • Destructor function is automatically invoked when the objects are destroyed.

  • It cannot be declared static or const.

  • The destructor does not have arguments.

  • It has no return type not even void.

  • An object of a class with a Destructor cannot become a member of the union.

  • A destructor should be declared in the public section of the class.

  • The programmer cannot access the address of destructor.

When is destructor called?
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called

#include<iostream>
using namespace std;
int count=0;
class Test
{
    public:
        Test()
        {
            count++;
            cout<<"\n No. of Object created:\t"<<count;
        }

        ~Test()
        {
            cout<<"\n No. of Object destroyed:\t"<<count;
            --count;
        }
};

main()
{
    Test t,t1,t2,t3;
    return 0;
}
Output
 No. of Object created:    1
 No. of Object created:    2
 No. of Object created:    3
 No. of Object created:    4
 No. of Object destroyed:    4
 No. of Object destroyed:    3
 No. of Object destroyed:    2
 No. of Object destroyed:    1

We appreciate you reading our blog, and we hope to welcome you again soon for more interesting posts. We appreciate your participation in our community and look forward to hearing from you.

0
Subscribe to my newsletter

Read articles from Rohan Kotkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rohan Kotkar
Rohan Kotkar