Why can I assign a new value to a reference, and how can I make a reference refer to something else?
-
- a) It cannot, the line you quote doesn't change the reference
q
, it changesp
. - b) No the literal is constant, but
p
is a pointer which points at a literal. The pointer can be changed, what is being pointed to cannot.q = "world";
makes the pointerp
point to something else.
- a) It cannot, the line you quote doesn't change the reference
You seem to think that this code
int i; int &j = i; int k; j = k;
is reassigning a reference, but it isn't. It's assigning the value of
k
toi
,j
still refers toi
. I would guess that this is your major misunderstanding.
An important detail about references that I think you're missing is that once the reference is bound to an object, you can never reassign it. From that point forward, any time you use the reference, it's indistinguishable from using the object it refers to. As an example, in your first piece of code, when you write
q = "World";
Since q
is a reference bound to p
, this is equivalent to writing
p = "World";
Which just changes where p
is pointing, not the contents of the string it's pointing at. (This also explains why it doesn't crash!)
As for your second question, references cannot be reassigned once bound to an object. If you need to have a reference that can change its referent, you should be using a pointer instead.
Hope this helps!
a) How can a reference q be reinitialized to something else?
It cannot be!
An reference variable remains an alias to which it was initialized at time of creation.
b)Isn't the string literal, p = "Hello", a constant/in read only space. So if we do,
No it doesn't.
char* &q = p;
Here q
is an reference to pointer of the type char p
. The string here is constant put the pointer is not, it can be pointed to another string, and the reference is alias to this pointer not the string literal so it is valid.
c) Second question I have is I have read about C++ reference type variables as they cannot be reinitialized/reassigned, since they are stored 'internally' as constant pointers. So a compiler would give a error.
int i;
int &j = i;
int k;
j = k; //This should be fine, but how we reassign to something else to make compiler flag an error
Does not reassign the reference. it changes the value of the variable to which it was alias.
In this case it changes the value of i
to k