I am currently learning the basics of C++ and I have found the following code:
#include <iostream>
using namespace std;
class MyClass {
int x;
public:
MyClass(int val) : x(val) {}
int& get() {return x;}
};
int main() {
MyClass foo (10);
foo.get() = 15;
cout << foo.get() << '\n';
return 0;
}
I don't understand why the line foo.get() = 15
works. To me it looks like a get and set at the same time. I guess it works due to the return type being int&
and not only int
.
Can someone explain to me how it works?
Thanks.