The sub-expression
returnA()
doesn't actually return `a' itself, but rather the value of `a'. Unfortunately, values are not variables -- and while you can assign things to variables, you cannot do the same to a value.
In C++-speak, the result of that expression is temporary (specifically it is a
prvalue), which occupies no storage (
it has no address) and will cease to exist at the semicolon. In other words, assigning to it doesn't make any sense.
If you want to assign
a
a value through the result, you can return a
lvalue reference to a. The reference refers to the variable a itself; all operations on references are treated as if applied to the referent.
1 2 3
|
int*& A::returnA(){ // return a lvalue reference to this->a
return this->a;
}
|
Another problem with your code is here:
1 2 3 4 5
|
void A::change(){
int s=10;
returnA()=&s;// uh oh - assigns an address of a local variable
return;
} // the lifetime of s ends exactly here
|
the local variable
s
ceases to exist when the function returns. This will leave
this->a
pointing to something which does not exist any more (a dangling pointer); any attempts to access
*a
would cause undefined behavior.