What is difference between pointer and reference in C++

(Last Updated On: February 25, 2019)

Before listing the difference between pointer and reference in C++ , lets see the definition of pointer and reference.

Pointer: A pointer is a simply variable that stores the address of another variable. The variable can also be another pointer.

Reference: A reference is a variable that refers to another variable. Or we can say an alias of a variable.

 

NOTE:

There is no reference concept in C language but in C++ only. There is only concept of pass by value and pass by pointers/address exist in C programming. But, normally,  people also use to say pass by reference in C to pass by address or pointers. You can read here pass by value and pass by pointers in C with example.

As per observations, generally, the difference between pointer and reference is one of the important C++ interview questions asked to freshers or 2 or 3 years experienced candidates  in the interviews .

 

C++ POINTER Vs REFERENCE

  • A pointer can be initialized with NULL but a reference can’t be NULL. Reference always refers to an object.
  • Pointers can be re-assigned but a reference can’t be re-assigned.
    In below example, Initially pointer ptr is assigned to address of variable “a” and re-assigned to address of another variable “b”. Reference “ref” is Initially assigned to variable “a” but on re-assigning it again with another variable “b”, compiler flashes an error.
  • Pointers can point to another pointer but reference cannot point to another reference.
  • Cannot get the address of a reference but we can get address of a pointer in C++.
  • Cannot have array of references but we can have array of pointers.
  • A pointer is de-referenced with * to access the value at memory location it points to, whereas a reference can be used directly.