C++ Reference Variable

C++ language allows you to create a new type of variable called reference variable.

Advertisements

What Is A Reference Variable ?

A variable that store values is called a value variable. The C++ reference variable is an alias for a value variable. It refers to the memory location of the value variable like pointer. Any changes in the value of reference variable can also change the value of variable that its referring to.

Syntax

<type> & <reference variable name> = <value variable name>;

Example#1

int number = 7;
int & prime_num = number;

To declare a reference variable, first declare a value variable. In above example it is the number.

The <type> is the data type of the reference variable, and & is the reference operator (not address of operator) followed by the <reference variable name>.

The above is example of a non const reference variable whose original value changes in the C++ program. What if we want to protect the original variable from any changes in reference variable ?

const Reference Variable

Any changes in the reference variable also change the value of original variable. However, const keyword prevent such changes. A const reference variable is a reference-to-const.

Syntax

const <type> & <reference variable name> = <value variable name>;

Example#2

// constant variable
const int digit = 15;
// reference to constant variable is valid
const int & ref_digit = digit;

Reference to const variable is valid. However, const reference to non const variable and non const reference to a constant is invalid. Consider two example given below.

Example#3

// non const reference to constant value is invalid
int & apples_stock = 34;

Similarly, const reference to non const variable will result in error. A variable which is not constant can change, therefore, reference to such variable is invalid.

Example#4

// non const variable 
double average = 23.87;
// const reference to non const is invalid
const double & ref_average = average; //error

The const reference variable can be Initialized to a different type or to a rvalue. We will discuss more about it in later.

Multiple References

You can declare and Initialize multiple references at the same time.

Example#5

//multiple references 
int a = 100, b = 200; 
int & x = a, & y = b;
int c = 300, & z = c;

Difference Between Pointer And A Reference Variable

A pointer variable and a reference variable work are the same. Both points to memory location of a value variable with a difference that the reference is more efficient and simple than a pointer.

The differences are:

  • Strict binding of reference variable to value variable and does not change, pointers are flexible.
  • Unlike pointers , Null cannot be assigned to reference variable.
  • Reference variables are simple, pointers need lot of dereferencing to access values.
  • You must free pointer memory after use, however, reference variable does not need to free memory.

Initializing And Strict Binding

The reference variable cannot be declared first and then Initialized like pointers because the reference variable is strictly bound to the value variable that it refers to. Once Initialized a reference cannot change. Therefore, a reference must be Initialized as soon as it is declared.

Example#6

int x = 30;
//reference to integer declared
int & y;
// invalid initialization
y = x; 

A pointer variable is declared first and can be Initialized later. Also, a variable is flexible, therefore, you can change the pointer to point to some other variable whenever you like.

Example#7

//declare a variable
float pi = 3.14;
// declare a pointer variable
float x;
// initialize pointer 
x = π 
// print current address
cout << " Address before change " << x << endl; 
// new variable 
float meter = 100.00;
// change pointer reference
x = &meter;
//print current address
cout << " Address after change" << x << endl; 

Output#7

Address before change 0x0045d567
Address after change 0x0063a975

Is it possible to change reference variable like pointer ? The program below answers this question.

Advertisements

Example#8

int num1 = 40;
// Reference to num1
int & mynum1 = num1; 
// New variable
int num2 = 500; 
//Try change reference 
mynum1 = num2; 
// Output memory addresses 
cout << " Address of Num2 = " << &num2 <<endl; 
cout << " Address of Reference mynum1 = " << &mynum1 <<endl; 

Output#8

Address of Num2 = 0x0065d675
Address of Reference mynum1 = 0x00624a765

The address are different because the reference variable mynum1 is still refering to num1. Only value of num2 is assigned to mynum1.

Null Assignment

The NULL is a macro that evaluates to 0 in C programming, but the it is a null pointer means its type casted using (void *)0.

The C and C++ NULL are not same where C++ does not allow (void*)0 definition of NULL. The C++ NULL should be integral constant expression that evaluates to 0. Therefore, a reference cannot be made to constant.

The C++-11, nullptr can be usd instead of NULL which implicitly converts to any pointer type it is assigned to.

A reference cannot be made to nullptr because it is not Initialized and does not point to any object.

Dereferencing Pointers

One of the major difference between pointer and reference variable is use of dereferencing operator. The pointers use dereferencing operator extensively to access values, whereas reference variables are simple to use.

Example#9

// swap using pointers
// function call 
swap(&a, &b);
//function definition
swap(int *a, int *b)
{
  int temp;
  temp = *a; //dereference a
  *a = *b; //dereference b
  *b = temp; 
}
//swap using reference variables x and y
//function call 
swap(x, y);
//function definition
swap(int & x, int & y)
{
   int temp; 
   temp = x; // direct assign x
   x = y ; // direct assign y
   y = temp; 
}

The reference variables are better because no need to send memory address to a function call like pointers. Secondly, no need to dereference those memory address to access values. The reference variable is sending the original values in the function call . 

We will discuss reference variables as function parameter in a separate article. 

Free Pointer Memory

The major drawback of pointer in comparison with reference variable is that a pointer memory must be freed after use because pointers hold separate memory spaces.

This not a problem with reference variable because its is an alias for the original value variable.

Example#10

// reference to function 
int & square (int a ) {
   int c = a * a; 
   int & res = c; 
   return res; 
}
// No need to free function square
int x = square (10); 

Now, consider the same function using pointers.

Example#11

//pointer to function 
int square(int b){
   int *res = b * b;
   return *res; 
}
// Now we must free pointer
int x = square(20);
free(res);

In the next article, we will discuss about the need for const keyword and reference variable as function parameters.



Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.