Reputation: 463
Recently, I am reading some books about C++ such as "C++ primer" and "Effective C++".Almost every books say that a reference cannot be changed. I am confused with this statement. Because, I can write down code like this.
int a = 1, b = 2;
int& c = a;
// then I can change the reference c without compile errors.
c = b;
So, I cannot understand what dost it mean a reference cannot be changed.
Upvotes: 1
Views: 1203
Reputation: 754
c = b;
In the above statement you are assigning the value of b
to the value of a
as c
is still referring to the the variable a
Upvotes: 0
Reputation: 2534
Pointers and reference are two mechanisms for referring to an object frome different places in a program without copying.
The consistence of reference can be understood by comparing with pointers.
char a{'a'};
char b{'b'};
char *p = &a;
p = &b;
The pointer
p
is pointer to different object changing from a
to b
.
In the case of reference:
char &r = a;
r = b;
The reference in expression is always dereferenced automatically. So it with change the value of the object it referenced.
Upvotes: 2
Reputation: 37192
Once a reference is assigned to a target any further use of that reference refers to the target, not the reference itself.
For example, int& c = a;
creates a reference called c
whose target is a
. But if you then try to change it, as in c = b;
you are changing the value of a
, not changing the target of c
.
Upvotes: 2
Reputation: 7390
When people say that a reference cannot be changed, they mean that you cannot change which object the reference is referencing... For example, with pointers, you can do this:
int a = 1, b = 2;
int *c = &a; // c points to a
c = &b; // c now points to b instead
*c = 3; // b now equals 3
There's no equivalent code for references. Once you initialize the reference:
int a = 1, b = 2;
int &c = a;
You can't change the reference so that the statement c = 3;
now changes b
instead of a
.
Upvotes: 6