Home > Back-end >  Does storing a returned reference into a variable allow you to access that variable?
Does storing a returned reference into a variable allow you to access that variable?

Time:09-18

I am confused as to why storing a reference to a member variable with an alias allows us to access it, while storing it with a variable does not allow us to access the same variable.

Let me clear up what I mean, say we have class Journey:

class Journey {
  protected:
      Coordinate start; //coordinate consists of x and y values
  public:
      Journey(Coordinate startIn,): start(startIn){} 
  //methods ......
  Coordinate & getStart(){ //returns a reference to the "start" member
    return start; 
  }
};
  • now say I do this
int main() {
    Journey j(Coordinate(1,1));
    Coordinate & a = j.getStart();  //function returns a reference and is stored under the alias "a"
    a.setX(0); //changes X value of the "start" member variable
    cout << j.getStart().getX() << endl; //returns 0 - as expected!
}
  • the example above works as I returned a reference to the member variable "start" and stored it under an alias and I accessed it to change the original member variable

  • But say I stored the reference to start under a variable instead

int main() {
    Journey j(Coordinate(1,1));
    Coordinate a = j.getStart();  //function returns a reference and is stored under the VARIABLE "a"
    a.setX(0); 
    cout << j.getStart().getX() << endl; //returns 1 - Original start was not changed?
}
  • I cannot do the same as a does not access the start member variable

I am not sure why this happens? What happened behind the scenes? We are storing the reference to start under a variable instead of an alias.

CodePudding user response:

Because you are calling a copy constructor when instantiating a Coordinate object with Coordinate a = j.getStart(). That is, Coordinate a is a copy of start, not a reference to it. Read here about copy constructors.

As for the question in the title, no, it doesn't. If you want some identifier to be a reference, you need to define it as a reference as you did in the first case.

CodePudding user response:

A reference is an alias for a variable.

In your first example, a is a reference, and by construction, it aliases j.start.

In your second example, a is not a reference and does not alias anything. How it is initialised (with a reference or otherwise) is irrelevant.

  • Related