2

According to this question you can't change what a reference refers to. Likewise the C++ Primer 5th Edition states

Once we have defined a reference, there is no way to make that reference refer to a different object. When we use a reference, we always get the object to which the reference was initially bound.

However the following code compiles and prints the value 4 which looks to me like the reference was changed?? Please elaborate if this is or is not so.

int a = 2;
int b = 4;
int &ref = a;
ref = b;
cout << ref;
Community
  • 1
  • 1
wal
  • 17,409
  • 8
  • 74
  • 109

2 Answers2

15

You are not reassigning a reference. A reference acts as an alias for a variable. In this case, ref is an alias for a, so

ref = b;

is the equivalent of

a = b;

You can easily check that by printing out the value of a:

std::cout << a << std::endl; // prints 4
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • If I am not `reassigning the reference` what is that called? I am using the assignment operator and in the context of a reference. Also, it may help if you post an illegal use of an attempted reassignment of a reference. – wal May 31 '13 at 16:48
  • @wal: It's just assignment. Your code is behaviourally very similar to `int *ref = &a; *ref = b; cout << *ref`. – Oliver Charlesworth May 31 '13 at 16:49
  • 3
    @wal I have explained what is going on. "You are doing the equivalent of `a = b;`". There is nothing illegal about that. You are just assigning a value to the variable that the reference refers to. – juanchopanza May 31 '13 at 16:49
  • thanks, that last comment cleared it up. it is subtly but importantly different from the 'equiavlent' c# so am glad I asked. – wal May 31 '13 at 17:07
  • 2
    @wal This can be quite a confusing issue, but once you think of a reference exactly as an alias, it all starts to make sense. – juanchopanza May 31 '13 at 17:10
1

You can understand how references work by comparing their behavior to that of a pointer. A pointer can be thought of as the name of the address of a variable; however a reference is just the name of the variable itself--it is an alias. An alias, once set, can never be changed whereas you can assign a pointer a new address if you want. So you have:

int main(void)
{
    int a = 2;
    int b = 4;
    int* ptr_a = &a;
    int& ref_a = a;

    ptr_a = &b;  //Ok, assign ptr_a a new address
    ref_a = &b;  //Error--invalid conversion.  References are not addresses.
    &ref_a = &b; //Error--the result of the `&` operator is not an R-value, i.e. you can't assign to it.

    return 0;
}
Matt Phillips
  • 9,465
  • 8
  • 44
  • 75