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 March 28, 2023 by Prepbytes

C++ is one of the most used object-oriented programming languages. And in these types of language, we have to deal with classes and objects a lot. And when declaring objects of the class we have the concept of constructors that are used to initialize the object and give the required memory to the object but once we cannot give the memory to the object for unlimited time in these types of scenarios we have the concept of destructor in c++ which deallocated the memory. While proceeding further in this blog, we will learn all about destructors in c++, followed by various examples, properties, and rules of destructors in c++.

What is a Destructor in C++?

Destructor in c++ is one of the special member functions that is automatically called when an object is destroyed. After calling the destructor the object will be destroyed and no other function will be called after that hence it is the last function that is called during the object’s lifetime. 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
A destructor in c++ is one of the special member function like a constructor that is called whenever the object is deleted or goes out of the scope. The destructor in c++ is responsible for all the cleanup work that prevents the code from a memory leak. In the above article, we have discussed the syntax, usage, properties, and examples of destructors in c++. Destructor is one of the most important features of c++ that allows the programmers to use the resources efficiently and also manages the memory.

Frequently Asked Questions

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

1. What happens if a destructor is not defined in C++?
If a destructor is not defined in C++, the compiler generates a default destructor that does nothing.

2. Can a destructor be virtual in C++?
Yes, a destructor can be virtual in C++. This is useful when a derived class may have additional resources that need to be freed.

3. What is a pure virtual destructor in C++?
A pure virtual destructor is a destructor that has no implementation.

4. Why is a pure virtual destructor useful in C++?
A pure virtual destructor is useful in C++ when a base class has one or more pure virtual functions. This ensures that any derived class that is created must provide its own destructor implementation.

5. Can a default destructor be overridden in C++?
No, a default destructor cannot be overridden in C++.

Leave a Reply

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