Difference between Pointer & Reference.
What are the differences between Pointers & References?
1. Both can be used to refer to any object of its type. But there is a difference in systax.
Eg:
int *p=&a;
int &r=a;
2. A pointer can be NULL, whereas a reference has to be always pointed to some object.
Eg:
1. Both can be used to refer to any object of its type. But there is a difference in systax.
Eg:
int *p=&a;
int &r=a;
2. A pointer can be NULL, whereas a reference has to be always pointed to some object.
Eg:
For pointers:
int *p; // This is valid.
int *p=NULL; // This is valid.
int *p=&a; // This is valid.
For references:
int &r; // This is In-valid.
int &r=NULL; // This is In-valid.
int &r=a; // This is valid.
3. A reference once it is binded to an object, it cannot be rebinded to a different object as, reference is inherently const.
Eg:
int a, b;
int *p=&a;
p=&b; // This is valid as it is a pointer.
int a,b;
int &r=a;
r=b; // This is invalid as a reference cannot be referenced to a different object.
Note: A reference can be considered as constant pointers, except that, even a const pointer can be pointed to NULL.
Comments