Defining variables with a return function?

(I am a noob, don't judge me)

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.
Last edited on
The ampersand means reference.

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 

okay, but why does ( foo.get() = 15; ) change the value of x, since ( .get() ) clearly only returns x?

PS: Minäkin olen suomalainen
foo.get returns a reference to X, then assigns the reference (which IS X) to 15.
Topic archived. No new replies allowed.