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.
Your foo.get is returning a reference to an int (noted int&).
References can be assigned (so they are l-values). Read the wikipage on C++ references, it is explaining better than I have time to. Or read carefully a good C++ programming book, like e.g. Stroustrup's Programming : Principles and Practice Using C++ or a Tour of C++ or The C++ Programming Language (or all of them!)
As Neil Kirk commented, you could nearly see references as a pointer implicitly dereferenced. In other words, and if you are familiar with C, think of int* get() { return &x; } and *foo.get() = 15;
See also this reference vs. pointer question
The line works because the function is returning a reference, that's semantically equivalent to:
int* get() {return &x;}
and:
*foo.get() = 15;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With