Why destructor does not take parameters in C++

Hello Folks!

Welcome to this tutorial. In this tutorial, we are going to discuss Why destructor does not take parameters in C++.

Many of you are having this question in your mind, why constructor can take parameters but not destructors?

So for understanding, this let’s first revise a little about destructors,

  • destructor, as the name indicates, is used to destroy the objects that have been created by a constructor. Just like a constructor, the destructor is a member function whose name is also the same as the class name. But unlike a constructor, it is followed by a tilde (~).
  • Here the definition itself answers the question that “why destructors do not take parameters”. Destructors are only used to clear the dynamic memory allocated to an object (through constructors) when it goes out of the scope.
  • And the main reason that constructors can take parameters, is that constructors not only create space for the objects but also initializes the members of the objects according to the parameters that we have passed to it.
  • On the other hand, there is no sense in passing arguments to a destructor as it will destroy the whole object otherwise.
  • Granting destructors to take arguments would also be a tough assignment for the compiler. The compiler will get confused about what arguments should it consume at the time of calling a destructor.

Now see an example of a destructor below:

#include<iostream>
using namespace std;
class DemoClass {
   private:
   int num1, num2;
   public:
   DemoClass(int number1, int number2) {
      cout<<"This is inside Constructor"<<endl;
      num1 = number1;
      num2 = number2;
   }
   void display() {
      cout<<"num1 = "<< num1 <<endl;
      cout<<"num2 = "<< num2 <<endl;
   }
   ~DemoClass() {
      cout<<"This is inside Destructor";
   }
};
int main() {
   DemoClass obj(3, 5);
   obj.display();
   return 0;
}

 

(Note:- It is always a good practice to use destructors in your program since it releases memory space for further usage.)

Thanks a lot for reading this tutorial!!!

Comment down for any queries.

Leave a Reply

Your email address will not be published.