Playing with Destructors in C++


Destructor is a function of a class in c++ that does the job of deleting the object of a class.

Calling a destructor

Destructor is called when the object of a class goes out of the scope in the program. The cases when object goes out of scope,

  • The program goes out of the scope of a function.

  • The program ends.

  • The block initializing local variables of object goes out of scope.

  • When the operator of the object is deleted.

Example

Let’s see a code and guess the output of the program,

 Live Demo

#include <iostream>
using namespace std;
int i;
class destructor {
   public:
      ~destructor(){
         i=10;
      }
};
int valueInitializer() {
   i=3;
   destructor d1;
   return i;
}
int main() {
   cout<"i = "<<valueInitializer()<<endl;
      return 0;
}

Output

i = 3

Let's understand the code first, here we have created a global variable I and then in the value initialized function we have changed its value. Here, we have initialized it with value 3 then created the object d1 and then returned the value.

Guess the output?

It’s 3, claps for you if you guessed it right and no worries if you thought it’s 10. Now, see what happened here,

As discussed above destructor is called when the calling function goes out of scope. And before going out of scope the function has returned the value 3 back.

Example

Give it another try guess the output of this block now,

 Live Demo

#include <iostream>
using namespace std;
int i;
class destructor {
   public:
      ~destructor(){
         i=10;
      }
};
int& valueInitializer() {
   i=3;
   destructor d1;
   return i;
}
int main() {
   cout<<"i = "<<valueInitializer()<<endl;
   return 0;
}

Output

This is a similar-looking code but this one

Prints : i = 10 instead.

Why?

Here, we have returned the variable reference instead of the value. So, when the destructor is called it changes the value to 10 and as the reference is passed 10 is printed.

Updated on: 17-Apr-2020

704 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements