pratapan
pratapan

Reputation: 167

C++ trying to reassign a reference to instance object

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?

Upvotes: 1

Views: 305

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 120051

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.

Upvotes: 1

user2100815
user2100815

Reputation:

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;

Upvotes: 1

Related Questions