top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are the differences between a pointer variable and a reference variable in C++?

+2 votes
750 views
What are the differences between a pointer variable and a reference variable in C++?
posted Sep 18, 2018 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

1:-Initalisation: A pointer can be initalised in this way:

int a = 10;
int *p = &a;
OR
int *p;
p = &a;
we can declare and initalise pointer at same step or in multiple line.

While in refrences,

int a=10;
int &p=a; //it is correct
but
int &p;
p=a; // it is incorrect as we should declare and initialise references at single step.

2:-Reassignment: A pointer can be re-assigned. This property is useful for implementation of data structures like linked list, tree, etc. See the following examples:

int a = 5;
int b = 6;
int *p;
p = &a;
p = &b;

On the other hand, a reference cannot be re-assigned, and must be assigned at initialization.

int a = 5;
int b = 6;
int &p = a;
int &p = b; //At this line it will show error as "multiple declaration is not allowed".

However it is valid statement,
int &q=p;

3:-Memory Address: A pointer has its own memory address and size on the stack whereas a reference shares the same memory address (with the original variable) but also takes up some space on the stack.

int &p = a;
cout << &(&p);

4:-NULL value: Pointer can be assigned NULL directly, whereas reference cannot. The constraints associated with references (no NULL, no reassignment) ensure that the underlying operations do not run into exception situation.

5:-Indirection: You can have pointers to pointers offering extra levels of indirection. Whereas references only offer one level of indirection.I.e,

In Pointers,
int a = 10;
int *p;
int **q; //it is valid.
p = &a;
q = &p;

Whereas in refrences,

int &p = a;
int &&q = p; //it is reference to reference, so it is an error.

Arithmetic operations: Various arithmetic operations can be performed on pointers whereas there is no such thing called Reference Arithmetic.(but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5).)

answer Jun 6, 2019 by Rushabh Verma R.
...