A destructor is a special member function of a class that is called if an object of that class gets out of scope or when the delete expression is used on a pointer to that class's object. A destructor will have the same name as the class, but it will be prefixed with a tilde (), and it will not be able to return any value or take any parameters. Destructor can be extremely useful for releasing resizable objects.

Destructor is useful for releasing resources before exiting a program, such as closing files and releasing memories.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

 Use of C++ Destructor

  • Object memory getting released.
  • The pointer variables' memory getting released.
  • Files and services getting closed.

 C++ Destructor Syntax

Class Name_of _class {

public:

 ~Name_of_class() //this is known as Destructor

   {

   }

}

Explanation

~Name_of_class() //this is known as Destructor: in this statement (~) followed by name of the class. This (~) symbol tilled represents destructor

Example Source Code:

// simple destructor program in C++

#include <iostream>

class desprogram

{       

         public:

         ~desprogram()

{

    std::cout<<"\ndestructor execution";

}

};

int main() {

         //object creation

         desprogram d1;

    return 0;

}

Output

Cpp_Destructor_1.

Explanation

The class desprogram has only one destructor, which is called desprogram in the example above. The destructor has a statement in it to print the destructor's execution as output. Since only one entity was made, the destructor can only be called once.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Properties of C++ Destructor

  1. When objects are destroyed, the destructor function is automatically named.
  2. It's not possible to declare it static or const.
  3. There are no arguments for the destructor.
  4.  It doesn't even have a void return form.
  5. A member of the union cannot be an entity of a class with a destructor.
  6. In the public section of the class, a destructor should be declared.
  7. The destructor's address is inaccessible to the programmer.

When is a Destructor Called?

The destructor will be called automatically when an object is no longer in scope and also in situations mentioned below

(1) The operation is completed

(2) The program is completed

(3) A block containing local variables is completed

(4) The delete operator is used

To identify the destructor from the normal function

  1. Destructors have the same name as the class, but with a tilde () before it.
  2. Destructors don't take arguments and don't give them back.

C++ Destructor Overloading

The destructor cannot be overloaded. It is not possible to overwhelm the destructor. In a class, we can only have one destructor. In a class followed by a class name, there can only be one destructor with no parameters and no return type.

Default Destructor and User-Defined C++ Destructor

If we don't write our own destructor in the class, the compiler generates one for us. If we have dynamically allocated memory or a pointer in the class, the default destructor works fine. We can write a destructor to release memory before the class instance is destroyed when a class includes a pointer to memory allocated in the class. To prevent memory leaks, this must be done.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Virtual C++ Destructor

When we have a virtual feature, it is always a good idea to render destructors virtual in the base class. Deleting a derived class object with a non-virtual destructor using a pointer of base class type causes undefined actions. A virtual destructor should be specified in the base class to correct this situation. Following a program, for example, results in undefined actions.

Sample Code For Virtual Destructor

// A program with virtual destructor in C++

#include <iostream>

using namespace std;

class base_class

{

public:

     base_class()

     {

cout<<"Constructing base_class \n";

}

     virtual ~base_class()

     {

 cout<<"Destructing base_class \n";

 }

};

class derived_class: public base_class {

public:

     derived_class()  

     { cout<<"Constructing derived_class \n"; }

     ~derived_class()

     { cout<<"Destructing derived_class \n"; }

};

int main(void)

{

derived_class *d = new derived_class();

base_class *b = d;

delete b;

getchar();

return 0;

}

Output

Cpp_Destructor_2

Explanation

In the above example, two classes were created. One class is base_class which acts as a parent class. Then this class has been derived into the derived_class. Both classes can have their own properties.

The base class destructor will be used to indicate the destroyed status of a base class object. Likewise the derived class destructor will be used to denote the destroyed status of an derived class object. But the destructor in inheritance concept, both will be executed at the time of derived class object deletion.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Rules for C++ Destructors

According to C++ destructor the statement should begin with a tilde () and the same class name.

  1. Destructors are not equipped with parameters or a return form.
  2. Destructors are invoked automatically and cannot be invoked manually from a program.
  3. Destructors cannot be overloaded.
  4. Which can be a virtual destructor.
  5. The Destructor will execute the reverse order of object creation.
  6. Destructor always present only in the public section.

Another Sample Code:

 // simple destructor program in C++

#include <iostream>

class desprogram

{

         private:

         int regno;

         char name[20];

         public:

         desprogram()

         {

         regno=20;

         }        

         void getdetail()

         {

    std::cin>>regno;

    std::cin>>name;

         }

         void showdetail()

         {

        std::cout<<"\nthe regno is  "<<regno;

        std::cout<<"\nthe name is   "<<name;

         }

~desprogram()

{

    std::cout<<"\ndestructor execution";

}

};

int main() {

         //object creation

         desprogram d1;

         d1.getdetail();

         d1.showdetail();

         desprogram d2,d3,d4;

         return 0;

}

Input:

11 mannna

Output

Cpp_Destructor_3.

In the above example, the four objects were created for the class desprogram. Therefore the destructor will be executed four times in the class object creation order.

Advance your career as a MEAN stack developer with the Post Graduate Program In Full Stack Web Development. Enroll now!

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Conclusion

C++ destructors are class members that remove an object. They are named when the class object is no longer in view, for example, when a method, a program, or a delete variable is called. Destructors vary from member functions in that they do not accept any arguments and do not return anything. Destructors are also given the same name as their class. 

In this article you learned about stack, implementation, operations with syntax and examples. To get expertise in C++ programming you can join our Simplilearn’s C++ certification training course. On the other hand we have also curated courses available for enthusiastic learners that are free of cost. You can explore the free courses and take the first step towards your next career goal.

If you are perhaps interested in a 360-degree learning on full stack development, do explore Simplilearn’s Post Graduate Program In Full Stack Web Development in collaboration with Caltech CTME. This coding bootcamp gives you all the job-ready knowledge and practical training you need to become a professional full stack web developer today.

Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on them, as soon as possible!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 30 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449