Advantages of reference variables over pointer variables in C++

This tutorial is about the advantages of reference variables over pointer variables in C++. A reference variable is an alias for a variable whereas a pointer variable points to an address occupied by some variable. Let’s understand how a reference variable can be a better option in some scenarios against the pointer variables.

A reference variable is a second name for a variable and can be used anywhere in the program as the original variable. A pointer variable is a variable that points to the address of a variable.

There are many advantages of using reference variables over pointer variables such as:

  • A reference variable does not consume any extra memory.  It has the same memory address as the variable it refers to. While a pointer needs extra space for itself.
  • In order to access the value of the referenced variable using pointer, we need to use a dereferencing operator(*) whereas we can do the same using reference variable without any dereferencing method.

Let’s understand with example programs.

While accessing the value of variables

Here is an example program that illustrates how we can access the content of a variable var1 using a reference variable ref_var and using a pointer variable. See the code.

#include <iostream>

using namespace std;

int main()
{
  int var1 = 4;
  
  //accessing value of var1 using reference variable
  int &ref_var = var1;
  cout << "Value of var1 (using reference variable): " << ref_var <<"\n";
  
  //accessing value of var1 using pointer variable
  int* p_var = &var1;
  cout<<"Value of var1 (using pointer variable): " << *p_var;
  
  return 0;
}

Output:

Value of var1 (using reference variable): 4
Value of var1 (using pointer variable): 4

Address of reference variables and pointer variables

In the below example we will see how the addresses are allocated for the reference variable and the pointer variable. See the code.

#include <iostream>

using namespace std;

int main()
{
  int var1 = 4;
  
  //decalring reference variable
  int  &ref_var = var1;
  
  //declaring pointer variable
  int* p_var = &var1;
  
  //printing address of var1 and ref_var and p_var
  cout << "Address of var1: " << &var1 << endl;
  cout << "Address of ref_var: " << &ref_var <<endl;
  cout << "Address of p_var: " << &p_var ;
  
  return 0; 
}

Output:

Address of var1: 0x6ffe14
Address of ref_var: 0x6ffe14
Address of p_var: 0x6ffe08

As you can see the addresses are different for pointer variable p_var and var1. That means the pointer variable does take extra memory to be stored. Also, we can see in the output that the address of the variables ref_var and var1 is the same. That means the reference variable ref_var did not take any extra space.

Thank you.

Also read: Pointers and references in C++

Leave a Reply

Your email address will not be published. Required fields are marked *