- Reference variables are aliases to other variables. Any changes to the original variable or the alias (reference variable) result in change to the same memory location.
- Reference variables must always be initialized.
- When pass by reference is done to functions unlike pass by value a new copy of the variable is not created. This is very useful when big objects are passed as class members.
- The other alternative is to use call by address using pointers. This involves de-referencing which may not look elegant and clean. References solve this problem.
EXAMPLE: Basic usage of reference variables
#include <iostream>
using namespace std;
int main()
{
int i = 100;
int &j = i;
cout << "i=" << i << endl;
cout << "j=" << j << endl;
j += 100;
cout << "i=" << i << endl;
cout << "j=" << j << endl;
cout << "Address of i=" << &i << endl;
cout << "Address of j=" << &j << endl;
}
OUTPUT:
i=100
j=100
i=200
j=200
Address of i=0012FF88
Address of j=0012FF88
EXAMPLE: Pass by references to functions
#include <iostream>
using namespace std;
// Pass arguments by reference
static void MySwap(int& i, int &j) {
int temp;
temp = i;
i = j;
j = temp;
}
int main()
{
int i = 10, j = 20;
cout << i << " " << j << endl;
MySwap(i,j);
cout << i << " " << j << endl;
}
OUTPUT:
10 20
20 10
0 comments:
Post a Comment