In C++ we can create a variable which can act as a reference variable to another existing variable, which means both the existing and reference variable has the same value and if there is a change in the existing variable then the change also occurs in the reference variable.
Reference vs Pointer variables
We often confuse the reference variable with pointer variables but both are different concepts, here are the three majors different between them.
- There could not be a NULL reference but we could have a NULL pointer.
- A reference variable must be initialized the moment it gets declared, but we can initialize the pointer variable value anywhere in the program.
- The reference variable always sticks to the one existing variable, once the reference variable is initialized with an existing variable you cannot refer it to another, but the pointers can be changed to any other variable.
Creating References variables in C++
A variable is a label to the data memory location, what if we want more than one variable to access that memory location and its content for that we can either use a pointer variable which holds the address of that data or we can create a reference variable which also acts as a label to data memory location. Though the core concept of pointers variable is similar to the reference variables, both are different concepts in C++. While creating a reference variable we need to pass the ampersand(&) operator along with the data type, for example, char& , int& , double& , etc. Reference variable Syntax:
Data_type& reference_variable = existing variable.
Reference variable Example:
#include <iostream> using namespace std; int main() { int ext_var= 100; int& ref = ext_var; // definng and initializing the reference variable ref cout<<"The value of ext_var is: "<<ext_var; cout<<endl; ext_var = 400; cout<<"Now the value of ref variable is: "<<ref; }
Output
The value of ext_var is: 100 Now the value of ref variable is: 400
Behind the Code Here in this example first we declare an Integer type variable int ext_var= 100, and then create an integer type reference variable int& ref = ext_var; Now the not only value of ext_var and ref is same but also the memory location of their data value or object, which mean both ext_var and ref variables pointing to the same data memory location.
References Quick Summary
- Reference variables are the variable that acts as a label to another existing variable.
- The concept of Reference variables is similar to the Pointers.
- The reference variable should be defined and initialized simultaneously.
- If the value of the existing variable changes than the value of the reference variable will also change.
People are also reading: