Search code examples
c++referenceconstants

Const reference not "updated"


I know this might be a common question, and I've seen similar ones asked on SO before. I am trying to wrap my head around that "return by const reference" stuff. I seem to be stuck at 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 by const int& prevents me from setting t.x using something like y=1, which is fine. However, I would have expected y to be 1 in the last line, but it remains zero, exactly as if getX() returned a plain int. What exactly is going on here?


Solution

  • While you return by reference, you save the result in the new integer y that has nothing to do with the member x from that point on. It is just a copy of t.x, its value after the point of initialization will not depend on the value or state of existence of t.x in any way.

    Use a reference to observe your desired behavior:

    #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
    }