Difference between pointer and reference in C++

Reference in C++ is like another name to a variable. A reference can only refer to a single variable.

int *p;
int n=10;
p = &n;
int m = 12;
p = &m;//fine. pointer can point to some other variable
int &r1=n;//r1 is reference to n
r1 = m;//r1 is not reference to m now but r1 and n are equal 12 now

Pointer can be allocated with new and deallocated using delete. Reference does not need new and delete.

Reference should be initialized when it is being defined. Pointer need not be. Only exception to this rule is when reference is parameter to a function, or a return value from a function or member of a class.

int &m;//error. m is not initialized
int *ptr;//fine. ptr need not be initialized

But both these let the parameter be modified by the function.

void swap(int *ptra, int *ptrb)
{
    int temp = *ptra;
    *ptra = *ptrb;
    *ptrb = temp;
}
void swap1(int&a, int &b)//reference parameters
{
     int temp = a ;
     a = b;
     b = temp;
}

Pointers inherited from C are more dangerous. References are not. As C++ programmer you must try to avoid using pointers. Use pointers only when you have to.

When large objects are to be passed as parameters to functions, passing them as pointers/references is faster than passing them by value.




Comments

Popular Posts