The reference to the constant is not "updated"

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; // why not 1?
}

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?

+4
source share
2 answers

, y, x . t.x, , t.x.

:

#include <iostream>
using namespace std;

class Test {
public:
  int x;

  Test(): x(0) {};

  const int& getX() const {
    return x;
  }
};

int main() {
  Test t;
  const int &y = t.getX();
  cout << y << endl;
  t.x = 1;
  cout << y << endl; // Will now print 1
}
+8

const int, const int y, , . .

+3

Source: https://habr.com/ru/post/1606180/


All Articles