Reputation: 30615
I was expecting the value of b to be 100 below, but I get 12. Why is this the case? Clearly my c = b
line is not assigning c as an alias for b?
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int a = 4;
int b = 12;
int& c = a;
c = 8;
cout << a << endl;
c = b;
c = 100;
cout << b << endl;
int bb;
cin >> bb;
return 0;
}
Upvotes: 1
Views: 943
Reputation: 272467
Clearly my
c = b
line is not assigningc
as an alias forb
?
Exactly, references cannot be reseated in C++. c
will always be a reference to a
.
c = b
is just a straightforward assignment.
Upvotes: 7
Reputation: 120711
c = b
in fact does the following:
c
is a reference to a
, so whatever operation we request on c
will actually work on a
.c
– that means, by 1., we must in fact assign to a
.a
is an lvalue of type int
, so assigning b
to it changes the value of a
to whatever value b
has at that moment. (For class-type objects, this would call the copy assignment operator.)b
has the value 12
, so we give this value to a
.And that's it. Nothing there changes anything about what c
refers to: it was a
previously, and it is a
afterwards, only a
now has a different value.
Apparently you want to reseat c
so that it then refers to b
. Well, you can't do that with C++ references, and IMO this is a good thing. But you can do it with pointers:
#include <iostream>
int main() {
int a = 4;
int b = 12;
int* c = &a;
*c = 8;
std::cout << a << std::endl;
c = &b;
*c = 100;
std::cout << b << std::endl;
return 0;
}
will output what you expected from your program.
Upvotes: 2
Reputation: 20616
You can't reseat references - your c = b;
line just assigns to c
(and thereby also to a
) the current value of b
.
When you then assign 100
to c
, b
therefore doesn't change, so it still has its original value of 12
when you print it out.
See this FAQ question:
http://www.parashift.com/c++-faq/reseating-refs.html
Upvotes: 6