Google

Advantages of reference variables over pointers in C++

Written on:May 8, 2013
Comments are closed




Advantages of reference variables over pointers in C++

A reference variable is an alias to a variable already defined. After a reference variable is created, the value can be referred to by the original variable or the reference variable. Whenever we declare a reference variable, we need to initialize it at that moment. Take for example, if an ans is an int type variable, defined as:

int ans = 5;         then
int & result = ans;

result is another name of ans, by which now we can refer to the value 5.

The following assignment

result = 10;

changes the value of both the variables to 10.


To create a reference variable &(ampersand) operator is used, where & in place of representing address represents a reference to the type of variable defined.

A pointer variable is a variable that contains the addresses of some other variable. In case of pointer variables, & operator is used to fetch the address of a memory location and * (asterisk) is the de-referencing operator that fetches the value stored in a pointer variable. One has to take care of such assignments when passing or receiving this value by reference, which are not needed in case of reference variables.  Moreover reference variables are used to pass arguments to a function by reference.

Sorry, the comment form is closed at this time.