1.

What are the differences between pointers and reference variables in C++?

Answer»

In C++, a pointer is a variable that keeps track of the memory address of another variable.

A reference is an alias for a variable that ALREADY exists. A reference to a variable that has been initialised cannot be MODIFIED to refer to another variable. As a result, a reference is analogous to a const pointer.

Pointer

  • Any time after a pointer is declared, it can be initialised to any VALUE.
 int x = 6;// some codeint *PTR = &x;

A reference is supposed to be initialized at its time of declaration.

int x = 6;int &ref = x;
  • It is possible to assign a pointer point to a NULL value. NULL references are not allowed.
  • A * must be used to dereference pointers. References can be referred to simply by their names.
  • A pointer can be altered to point to any similar-type variable. For example:
int x = 6;int *ptr;ptr = &x;int y = 7;ptr = &y;

A reference to a variable OBJECT cannot be modified once it has been initialised to a variable.



Discussion

No Comment Found