Showing posts with label computer science technicall material. Show all posts
Showing posts with label computer science technicall material. Show all posts

Saturday, July 18, 2009

Difference between pointer and reference in C++

pointer and reference in c

Puppy! Can Move/Change? -  is a *Pointer in C++

reference in c

Statue! – Can’t change  - is a &reference in C++

Correct code -

int *p = &i;

int k;

p = &k;

Incorrect code -

int &b = a;

int c;

int &b = c;

While creating a reference, it has to be necessarily initialised to some variable or an object. Trying to create a standalone reference i.e. int &b; and then assigning it to some variable i.e. b=a; will not only generate an error, but would also be meaningless, since at the time of its creation itself, a reference has to refer to some variable.

Although references are internally maintained using pointers, there's a subtle difference between a pointer and a reference. The address contained in a pointer variable may be changed at any point in the program that makes it a flexible connection. However a reference once created, cant refer to any other object thus it is a rigid connection.

A pointer has to be de-referenced before you can access the value at the address contained in it. A reference is moreover a direct connection as its just another name for the same memory location.

You can have an array of pointers whereas you cannot have an array of references.

 

 

Followers