#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;
}
views:
93answers:
5I 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)
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.
Your are not assigning a new variable (referee) to b
, but a new value to the variable b
refers to, in this case a
.
Reference is not pointer at all.
int const & b1 = a; // const reference
int & b2 = a // non-const reference
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.