I know this can be a common question, and I've seen people like that ask about SO before. I am trying to wrap my head with "return by const reference". I seem to be stuck with this seemingly simple example:
#include <iostream>
using namespace std;
class Test {
public:
int x;
Test(): x(0) {};
const int& getX() const {
return x;
}
};
int main() {
Test t;
int y = t.getX();
cout << y << endl;
t.x = 1;
cout << y << endl;
}
I understand that returning const int & does not allow me to set tx using something like y=1, which is fine. However, I would expect y to be 1 in the last line, but it would remain zero, as if getX () returned a simple int. What exactly is going on here?
source
share