Predict the output of the below code snippet.
Output of the above program is “i = 3”.
Why the output is i= 3 and not 10?
While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3.
How to make the program to output “i = 10” ?
Following are two ways of returning updated value:
1) Return by Reference:
Since reference gives the l-value of the variable,by using return by reference the program will output “i = 10”.
The function foo() returns the l-value of the variable i. So, the address of i will be copied in the return value. Since, the references are automatically dereferened. It will output “i = 10”.
2. Create the object ob in a block scope
Since the object ob is created in the block scope, the destructor of the object will be called after the block ends, thereby changing the value of i to 10. Finally 10 will copied to the return value.
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Destructors in C++
- C++ | Destructors | Question 1
- C++ | Destructors | Question 2
- C++ | Destructors | Question 3
- C++ | Destructors | Question 4
- C++ Interview questions based on constructors/ Destructors.
- Program to copy the contents of one array into another in the reverse order
- Interesting facts about C Language
- Is body of a Default Constructor blank in C++?
- Program to Reverse a String using Pointers
- clocale header file in C++
- Difference between Structure and Array in C
- Structured Programming Approach with Advantages and Disadvantages
- Commonly used String functions in C/C++ with Examples