C++ References

A reference is essentially an implicit pointer that acts as another name for an object. One important use for a reference is to allow you to create functions that automatically use call-by-reference parameter passing rather than C++’s default call-by-value method. When you create a reference parameter, that parameter automatically refers to (implicitly points to) the argument used to call the function. When you assign a value to a reference, you are actually assigning that value to the variable that the reference refers to. In the case of function parameters, this will be variable used in the call to the function. Also, no copy is created.

Below is a simple C++ program illustrating the use of references.

#include <iostream>

using namespace std;

void swap(int &i, int &j);

main(){
    int a = 1, b = 2;
    
    cout << "a & b: " << a << ", " << b;
    swap (a,b); // no & operator needed
    cout << "\nNow a & b:" << a << ", " << b;
    return 0;
}

void swap (int & i, int &j){
    int temp = 0;
    temp = j; // no * operator needed
    j = i;
    i = temp;
}

Output:

a & b: 1, 2  
Now a & b:2, 1  

Passing References to Objects

The main advantage of passing objects by reference is that the objects destructor function is not called every time when the called function terminates. No copy of the object inside the function will affect the original object outside the function. Below is a simple C++ program that illustrates this concept –

#include <iostream>

using namespace std;

class c1{
    int id;
    public:
          int i;
          c1(int i);
          ~c1();
    void neg(c1 &ob1) { ob1.i = -ob1.i; } // no temp object created
};

c1::c1(int num){
    cout << "\nconstructing:" << num;
    id = num;
}

c1::~c1(){
    cout << "\ndestructing:" << id;
}
main(){
    c1 ob1(1);
    ob1.i = 10;
    ob1.neg(ob1);
    cout << "\n" << ob1.i << "\n";
    return 0;
}

Output:
constructing:1   
-10                                                                                                              
destructing:1

Below C++ program shows implementing returning of references –

char &replace(int i);
char s[80] = "Good Day"; // return a reference

main(){
    replace(5) = 'X'; //assign X to space after Good
    cout << s;
    return 0;
}

char &replace(int i){
    return s[i];
}

Output:
  Good Xay

The replace() is declared as returning a reference to a character array. As replace is coded, it returns a reference to the element of ‘s’ that is specified by its argument ‘i’. The reference returned by replace() is then used in main() to assign to that element the character ‘X’.