What is difference between pointer and reference in C++

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.

IT Jobs Made Easy For Freshers
int a = 3;
int *ptr = &a; //pointer has address of int variable "a".
int &ref = a; // reference "ref" is referring the variable "a"

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

1) A pointer can be initialized with NULL but a reference can’t be NULL. Reference always refers to an object.

int a=3; int &ref = a;// OK 
int *ptr= NULL //OK 
int &ref = NULL Or 0;// Error : 'initializing' : cannot convert from 'int' to 'int &'. 

2 ) 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.

int main(){ 

int a = 3;// define a variable 
int *ptr = &a; //pointer has address of int variable "a". 
int &ref = a; // reference "ref" is referring the variable "a" 
int b=5;//define another variable. // ptr can point to another variable b
ptr = &b;  // reference can't point to another variable b as because it is already referencing variable a 
ref = &b; // compiler error return 0;

 } 

3) Pointers can point to another pointer but reference cannot point to another reference.

4) Cannot get the address of a reference but we can get address of a pointer in C++.

5) Cannot have array of references but we can have array of pointers.

6) A pointer is de-referenced with * to access the value at memory location it points to, whereas a reference can be used directly.

.

What is difference between pointer and reference in C++

Scroll to top