Steve Steve - 3 months ago 6
C++ Question

Reference in lhs and rhs difference in C++

I am learning C++ and I found that when a reference is on the right hand side, there can be two cases. Suppose I have a method:

int& GetMe(int& i) { return i; }


And I have:

(1)
int j; GetMe(j) = GetMe(i);


and

(2)
int& k = GetMe(i);


The consequences of (1) and (2) are different. In (1), the semantic is to copy the value of
i
into
j
. The addresses of
i
and
j
are remained the same. Changing
i
doesn't affect
j
at all. Actually this is the case when you overload the index operator[] and use the index operator for assignment. In (2), the semantic is to create a referent of
i
as
k
.
k
has the same address as
i
and changing
i
affects
k
.

So why do we have the differences? I think, in C++, a reference's address is determined once and only once. Once a reference's address is determined, it can never be changed later. In (1), the reference of
j
is determined before, so the action is to copy value from
i
to
j
. In (2), the reference of
k
is being declared and initialized so it is done using reference of
i
. So the action is reference initialization.

I didn't find material explicitly saying above things so I want confirmation. Anyone knows reference well in C++ must can help me or point me to clear material. Thank you very much in advanced.

Answer

What you are missing here is that type of variable is different and it is all that matters. In first example you have int j and in second - int &k.

References in functions prototypes exists in different grounds, they looks the same, underneath they are pretty much the same but they used differently because they exists only when method is executing.

Actually, your code is dong exactly following

int j;
int & j1 = j;
int & i1 = i;
j1 = i1;

versus

int & i1 = i;
int & k = i1;

It's easy to see that in first case two references actually reference different variables i.e. different parts in memory but in second case they all reference the exact same variable. Hence the difference.