Wednesday, September 1, 2010

What is the difference between reference type and pointers.

Difference 1>
Reference must point to valid objects at the time of
declaration where pointer need not point to valid objects
at the time of declaration means
int nvalue=5;
int &rnvalue; //This is invalid.
int &rnvalue=nvalue; //This is valid.

But
int *rnvalue; //This is valid.
rnvalue=&nvalue;
Difference 2>
Pointer is a variable which holds the address of another
variable.
But Reference is another name of the same variable.





In addition to the previous answer given in Answer #1,
namely References must point to valid objects at the time
of declaration, references also has the following
limitation.

Once a reference is assigned, there's no way you can modify
the reference. However for a pointer type, variable
assignment is legal.

e.g.,

int i, j;

int *pi, *pj;

pi = &i; // pointer to i
pj = &j; // pointer to j

int &k = i; // reference to i

pi = pj; // pi no longer points to i, instead
// it is now pointing to j
k = j; // The reference k is still with i, it is only
// the value of i that is now modified. i is
// assigned the value of j

No comments:

Post a Comment