- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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,
#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,
#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.