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.