In a book, I came across this, "When an object is returned by a function, a temporary object is automatically created that holds the return value. It is this object that is actually returned by the function. After the value has been returned, this object is destroyed."
I am not able to fully understand what is being said here precisely.
// Returning objects from a function.
#include <iostream>
using namespace std;
class myclass
{
int i;
public:
myclass()
{
cout << "constructing: " << i << endl;
}
~myclass()
{
cout << "destructing: " << i << endl;
}
void set_i(int n) { i=n; }
int get_i() { return i; }
};
myclass f(); // return object of type myclass
int main()
{
myclass o;
o = f();
cout << o.get_i() << "\n";
return 0;
}
myclass f()
{
myclass x;
x.set_i(1);
return x;
}
The above program gives the following output.
constructing: 0
constructing: 3935896
destructing: 1
1
destructing: 1
My question is:
When "x" is being returned from f(), a temporary object should have been created according to the book. However, no "constructing: " is printed because a copy of "x" is being created, so calling a constructor is redundant (this is the same reason due to which, while passing an object to a function, only its destructor gets called).
But, when that temporary object is destroyed, why it's destructor is not called?