What is a reference variable?
A reference is defined as an alias for another variable. In short, it is like giving a different name to a pre-existing variable. Once a reference is initialized to the variable, we can use either the reference name or the variable to refer to that variable.
Creating references in C++
The basic syntax to create a reference is –
Data type& new variable = previous variable
The newly created variable will now refer to the previous variable.
For example –
int i = 17 // The variable i is declared as 17
Creating the reference of i will be as –
int& x = i // Here x will be called as the integer variable initialised to r
C++ code
Output
Difference between Reference and Pointers
References | Pointers |
---|---|
We cannot have a NULL reference. | The concept of NULL pointers is allowed. |
A reference assigned to a particular object cant be changed. | Pointers, on the other hand, can point to different objects at any time. |
A reference is also initialized at the time of its creation. | Pointers can be initialized at any time. |
Next TopicFriend Function in C++