I was on cplusplus.com/doc/tutorial and saw this code:
class MyClass {
int x;
public:
MyClass(int val) : x(val) {}
int& get() {return x;}
};
int main() {
MyClass foo (10);
foo.get() = 15;
}
How does calling foo.get() = 15 change x? I don't see anything defining it that way since there is only return x; in the body. And also if I don't include the ampersand, it removes this feature? I've looked on the net but haven't found a direct explanation.
The function does not return a (copy of a) value; it returns a reference to the (member) variable foo.x.
Reference is an alias, another name. We can access a variable via reference like we access it directly. (Except in this case the variable is private member and not actually directly accessible.)
1 2 3
int foo = 7;
int & bar = foo;
bar = 42; // same as foo=42