#include
using namespace std;
int main()
{
int x = 10;
int& ref = x; // ref is a reference toward x.
ref = 20; // Value regarding x is now changed toward 20
cout << "x = " << x << endl ;
x = 30; // Value regarding x is now changed toward 30
cout << "ref = " << ref << endl ;
return 0;
}
Output:
x = 20
ref = 30
Following is one more example that uses references toward swap two variables.
#include
using namespace std;
void swap (int& first, int& second)
{
int temp = first;
first = second;
second = temp;
}
int main()
{
int a = 2, b = 3;
swap( a, b );
cout << a << " " << b;
return 0;
}
Output:
3 2
References vs Pointers
Both references furthermore pointers can be used toward change local variables regarding one function inside another function. Both regarding them can also be used toward save copying regarding big objects when passed as arguments toward functions or returned from functions, toward get efficiency gain.Despite above similarities, there are following differences between references furthermore pointers.
References are less powerful than pointers
1) Once a reference is created, it cannot be later made toward reference another object; it cannot be reseated. This is often done with pointers.
2) References cannot be NULL. Pointers are often made NULL toward indicate that they are not pointing toward any valid thing.
3) A reference must be initialized when declared. There is no such restriction with pointers
Due toward the above limitations, references in C++ cannot be used beneficial to implementing data structures like Linked List, Tree, etc. In Java, references don’t have above restrictions, furthermore can be used toward implement all data structures. References being more powerful in Java, is the main reason Java doesn’t need pointers.
References are safer furthermore easier toward use:
1) Safer: Since references must be initialized, wild references like wild pointers are unlikely toward exist. It is still possible toward have references that don’t refer toward a valid location (See questions 5 furthermore 6 in the below exercise )
2) Easier toward use: References don’t need dereferencing operator toward access the value. They can be used like normal variables. ‘&’ operator is needed only at the time regarding declaration. Also, members regarding an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed toward access members.
Together with the above reasons, there are few places like copy constructor argument where pointer cannot be used. Reference must be used pass the argument in copy constructor. Similarly references must be used beneficial to overloading some operators like ++.