views:

93

answers:

5
#include<iostream.h>

int main()
{
int a=10;
int &b=a;

cout<<"B"<<'\n'<<b;
cout<<"A"<<'\n'<<a;
b=100;
cout<<"B"<<'\n'<<b;
cout<<"A"<<'\n'<<a;
int c=20;
b=c;

cout<<"C"<<'\n'<<c;
cout<<"B"<<'\n'<<b;
}
+3  A: 

I hope you are not getting confused with :

b=c;

This will only assign the value of c to b. It will not refer to c. ( It will still refer to a itself)

aJ
+6  A: 

A reference is not a const pointer. A const pointer would need to be dereferenced to access the value. You don't need to dereference references.

A reference is an alias - a new name for the same thing. So the code in your question is valid and a and b refer to the same thing.

Mark Byers
+3  A: 

Your are not assigning a new variable (referee) to b, but a new value to the variable b refers to, in this case a.

Space_C0wb0y
A: 

Reference is not pointer at all.

int const & b1 = a; // const reference
int       & b2 = a  // non-const reference
Alexey Malistov
Can we say that ref is initialized to one var and then it cant point to other variable.
sandeep
Yes, we can. But the value of this `other variable' can be changed.
Alexey Malistov
I assume it's the value of the 'one var', not 'other variable' that can be changed, you meant.
mlvljr
+2  A: 

A reference is similar to a const pointer but not to a pointer to const object.

const int* p; //can't change the value of *p
int* const p; //can't change p (make it point to a different int)

References are similar to the latter - once initialized, they can't be made to refer to another object.

visitor