Hi,
In C++, we can use function calls on L value (left side of assignment operator) where the function returns non-const reference object.
It looks something like f()=10;
But i didnt understand the usage of the above statement, how the value 10 is given to function f() and where does return value of f() gone?
You're not assigning 10 to the function, just like when you do a=f(), you're not assigning the function to a. You're assigning 10 to [the data that's pointed to by the reference that's returned by the function].
1 2 3 4 5 6 7 8 9
int a=-1;
int &f(){ return a; }
int main(){
std::cout <<a<<std::endl;
f()=1;
std::cout <<a<<std::endl;
}
As for the return value of f() (a reference to data), just like all data (a reference to data and a pointer to data are both also data) that's returned by a function, it is destroyed at the end of the statement.
helios: Thanks for your reply.
What is the practical advantage of this feature?
As i understand from your explanation, We are executing a function f() and assigning the R value(1) to the return object of the function f(). In addition, you are telling that the object will be destroyed after the functions returns as its L-Value. I didnt understand the advantage or practical usecase to use the above statement.
assigning the R value(1) to the return object of the function f(). In addition, you are telling that the object will be destroyed after the functions returns as its L-Value.
No, you misunderstood. It's not the object whose value has changed that will be destroyed, it's the reference that pointed to that object.
Consider this:
1 2 3 4 5
int a;
{
int &b=a;
b=1;
}
At the end of the block, it's b that will go out of scope, not a. a will continue to exist with its modified value.