1

Trying to understand how reassignment of references is blocked in C++. I understand that as in Reassigning C++ reference variables the reference itself cant be reassigned but the value of the refree is being changed. But I want to understand how this works for instance objects

For below code

class A{};

A aobj;  
A& aref = aobj;
A bobj; 
aref = bobj;  

Want to understand if above is legal and whats happening here.

If its legal then I am not able to understand how does it work. Are we just changing the value the variable 'aobj' holds? Then isent that same as 'aref' referring now to object 'bobj'

If its illegal is it considered as an attempt to reassign a reference?

pratapan
  • 157
  • 7
  • 3
    "*I understand that ... the reference itself cant be reassigned but the value of the refree is being changed*" If you understand that, it isn't clear why you're asking the question. – juanchopanza Jun 25 '17 at 15:11

2 Answers2

1

It's legal. What this does:

aref = bobj;

is assign bobj to aobj. The reference aref is not re-seated; it still refers to aobj. But now aobj is a copy of bobj, assuming sensible assignment semantics. In other words, it's the same as if you had said:

aboj = bobj;
1

If aref refers to aobj, then aref behaves exactly the same as aobj in most contexts (by definition).

In particular, aref = bobj has exactly the same effect aobj = bobj would have. There's nothing more to it. aref doesn't suddenly stop referring to aobj and start referring to bobj just because you did aobj = bobj, so aobj = bobj doesn't have this effect either.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243