[SOLVED] Does storing a returned reference into a variable allow you to access that variable?

Issue

This Content is from Stack Overflow. Question asked by MohG

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.



Solution

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.


This Question was asked in StackOverflow by MohG and Answered by Kaiyakha It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?