Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Destructor in C++

Last Updated on January 8, 2024 by Ankit Kochar

In C++, the concept of a destructor plays a pivotal role in managing memory and resources. It is a special member function that gets invoked automatically when an object goes out of scope or is explicitly deleted. Destructors primarily handle the clean-up activities, releasing memory allocations and resources acquired during an object’s lifetime. Understanding destructors is crucial for efficient memory management and preventing resource leaks in C++ programs.

What is a Destructor in C++?

In C++, a destructor is a special member function within a class that is automatically called when an object of that class is destroyed or goes out of scope. Its primary purpose is to perform cleanup tasks and release resources held by the object before its memory is deallocated. The name of a destructor is the class name preceded by a tilde (~).
Destructors are the counterparts to constructors in C++. While constructors initialize an object’s state and allocate resources, destructors ensure proper cleanup and deallocation of those resources, such as freeing memory, closing files, releasing network connections, or performing any necessary cleanup operations specific to the object.
The destructor in c++ is used to release or clean up all the resources that are used or allocated to the object during its lifetime.

  • It will have the same name as that of the class followed by the ‘~’ symbol.
  • It will destroy the object created by the constructor.
  • Destructor in c++ does not require any argument and it also doesn’t return any value.
  • All the memory space occupied by the constructor is released by destructors in c++.
  • There can be only one destructor in c++ of a single class.
  • There is no need to call the destructor in c++ explicitly it will be called automatically when the object goes out of the scope.
  • The destructor in c++ destroys the objects in the reverse or opposite order of their creation.

Syntax of a Destructor in C++

The syntax of a destructor in c++ is quite simple as we have to name the destructor as that same class name just followed by a tilde(~) symbol.

~MyClass() {
// Code to perform cleanup or release of resources
}

This is the syntax for declaring the constructor outside the class.
MyClass: ~MyClass() {
// Code to perform cleanup or release of resources
}

Here we have the destructor of the class “MyClass”. We have discussed two methods for declaring the destructor first is to declare the destructor inside the class and the second is to declare the destructor outside the class. The destructor function has no return type and takes no arguments.

When is a Destructor in C++ Called?

There are many cases where a destructor in c++ is called and they are mentioned below.

  • When the object is destroyed or goes out of scope.
  • When the object is explicitly deleted.
  • When an exception is thrown.
  • A block counting the local variable ends.
  • The program ends.

Usage of a Destructor in C++

There are many use cases of destructor in c++.

  • It is used for resource cleanup by the objects.
  • Used for memory deallocation taken dynamically by the objects during their lifetime.
  • Prevents memory leaks by releasing non-utilized resources.
  • It is also responsible for state cleanup i.e, modifying the state of an object.

Properties of Destructor in C++

Some of the properties of destructor in c++ are given below:

  • The destructor in c++ is automatically called or invoked when objects are destroyed.
  • It does not have any return type not even void.
  • There are no arguments in destructor in c++.
  • The programmer or developer cannot access the address of the destructor.
  • We cannot make the object of the class which has the destructor as the member of the union.
  • It can’t be declared constant or static.
  • If you are declaring a destructor in c++ then it should be declared in the public section of a class.

Examples of Destructor in C++

In this section, we will discuss various examples of destructor in c++.

Example 1 of Destructor in C++: With Various Objects
In this example we will see the implementation of a destructor in c++ for various objects created by the constructor.

Code Implementation

#include<iostream>
using namespace std;
int count=0;
class practice
{
    public:
        practice()
        {
            count++;
            cout<<"\nObject created:\t"<<count;
        }
        
        ~practice()
        {
            cout<<"\nObject destroyed:\t"<<count;
            --count;
        }
};

main()
{
    practice t,t1,t2,t3;
    return 0;
}

Output

Object created: 1
Object created: 2
Object created: 3
Object created: 4
Object destroyed:   4
Object destroyed:   3
Object destroyed:   2
Object destroyed:   1

Explanation of the above code
In the above example we have a class name practice and in that class, we have created a constructor and a destructor and we have shown that for eerie object creation, the constructor and object both are created and one by one all the objects are deleted in the reverse order of their creation.

Example 2 of Destructor in C++: Flow of Instructions
In this example, we will see the step-by-step representation of the instructions and conditions that happen when we create an object.

Code Implementation

#include<iostream>
using namespace std;
class Demo {
   private:
   int num1, num2;
   public:
   Demo(int n1, int n2) {
      cout<<"Inside Constructor"<<endl;
      num1 = n1;
      num2 = n2;
   }
   void display() {
      cout<<"num1 = "<< num1 <<endl;
      cout<<"num2 = "<< num2 <<endl;
   }
   ~Demo() {
      cout<<"Inside Destructor";
   }
};
int main() {
   Demo obj1(15, 25);
   obj1.display();
   return 0;
}

Output

Inside Constructor
num1 = 15
num2 = 25
Inside Destructor

Explanation of the above example
In the above example we have created an object and we have seen all the sequence-wise calls of instructions first the constructor in called after that all the operations that we want to perform with that object and at last when there is no more need of object then the destructor.

You can also use virtual destructor in c++.

Conclusion
In conclusion, comprehending the significance of destructors in C++ programming is fundamental for robust memory management. Destructors enable automatic cleanup of resources, preventing memory leaks and ensuring efficient usage of system resources. By properly implementing destructors, developers can enhance the reliability and performance of their C++ applications while adhering to good coding practices and principles.

Frequently Asked Questions Related to Destructor in C++

Below are some of the frequently asked questions about destructor in c++.

1. Are destructors inherited in C++?
Yes, in C++, destructors are inherited like other member functions. If a base class has a virtual destructor, it is recommended to declare the derived class’s destructor as virtual as well to ensure proper cleanup of resources when using polymorphism and dynamic memory allocation.

2. What is the naming convention for a destructor?
In C++, the destructor’s name is the class name preceded by a tilde (~). For example, the destructor for a class named MyClass would be written as ~MyClass().

3. Can a destructor have parameters?
No, a destructor in C++ does not take any parameters, nor does it return any value. Its primary purpose is to perform cleanup activities for the class instance it belongs to.

4. When is a destructor called?
A destructor is automatically called when an object goes out of scope, such as when the object is local to a function and the function ends. Additionally, it is invoked when delete is explicitly used to deallocate memory for dynamically allocated objects.

5. What happens if a destructor is explicitly called?
Explicitly calling a destructor in C++ using its name (e.g., myObject.~MyClass()) is not recommended and can lead to undefined behavior. Destructors should be left to execute automatically by the compiler.

6. Can multiple destructors be defined for a single class?
No, in C++, only one destructor can be defined for a class. The compiler automatically generates a default destructor if none is explicitly declared by the programmer.

7. Can exceptions be thrown from a destructor?
It is generally advised to avoid throwing exceptions from destructors. If an exception is thrown during the execution of a destructor, the program’s behavior can become unpredictable and might result in memory leaks.

8. Do destructors deallocate memory for member variables?
Destructors primarily handle cleanup tasks and releasing resources held by objects. If an object holds dynamically allocated memory or resources, the destructor should free those resources to prevent memory leaks.

Leave a Reply

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