A reference is just giving another name to an existing object or variable.
- References must be assigned with some object at the time of declaration.
- Once the references are initialized with some object or variable, they cannot be changed later.
- Unlike pointers, we cannot create an array of references.
- References don’t have their own identity. When we try to get the address of the reference variable using ‘&‘ we will get the address of the variable to which it is referring.
- The size of stack space allocated for the reference variables varies from machine to machine. In a 32-bit machine, it is 4Bytes whereas in a 64-bit machine it is of 8Bytes.
There is nothing we can do with references that we cannot do with pointers. Both are almost the same with just a syntactic difference.
When we use them in our program references look a bit cleaner than the pointers.
Following is the syntax to declare the reference variable
<TYPE>& ref_name = object_to_point;
int& ref = a;
How to declare and use a reference variable in c++?
#include <iostream>
int main() {
int a = 10;
// Created a ref and referenced it to variable 'a'.
int& ref = a;
// Accessing the value of 'a' using "ref"
printf("%d", ref);
// Modifying the value in 'a' using "ref"
ref = 20;
printf("%d", a);
return 0;
}
The following program gives a compilation error because the reference variable must be initialized with an object.
#include <iostream>
int main() {
int a = 10;
// Created a ref but did not initilized it with an object.
int& ref;
printf("%d \n", ref);
ref = 20;
printf("%d", a);
return 0;
}
I hope you got the overview of references and how to use them in C++✌️