Reference types - Introducing

Ampersand & is used to:

  • represent the address-of operator for obtaining address of a variable

  • denote a reference to another variable (alias)

You declare a reference type using a syntax similar to declaring a pointer variable. That is, you declare the data type of the C++ variable or object that will be referred to, then you use the & character followed immediately by the reference type name. Finally, it's important to note that when declaring a reference, you must assign it at that time. It behaves similar to a constant in this sense. An example demonstrates the declaration.

    int num = 3;
    int &refNum = num;  //& tells us that refNum is a reference value; 
                        //assign it to the num variable
                        //This binds refNum to num
                        //This reference cannot be reassigned later in program code

    int &refNum2;//this line cause an error because it is not initilized


    cout << refNum << endl; //result is 3, because refNum is an alias or reference to num, which 
                            //holds the value 3

To see how this affects the original value of num, let's create another small code sample that displays the value for num, modifies it through refNum, then outputs the memory addresses of num and refNum.

    int num = 3;
    int &refNum = num;

    cout << "num contains " << num << endl;
    cout << "refNum contains " << refNum << endl;

    refNum++;    // increment refNum by 1
                 // which will also increment num due to refNum bing an alias for num    

    cout << "num contains " << num << endl; //shows 4 as refNum

    cout << "refNum contains " << refNum << endl; //output the memory address of num and refNum
                                                  //shows that they both point to the same memory location
                                                  //Hence, any changes made to refNum affect num 


    cout << "refNum is located at " << &refNum << " and num is located at " << &num << endl;

If we add the above code with :

    num++;
    std::cout << "num contains " << num << std::endl;  //shows 5
    std::cout << "refNum contains " << refNum << std::endl;  //shows 5
    std::cout << "refNum is located at " << &refNum << " and num is located at " << &num << std::endl;


   //Since refNum is an aliase of num, when there is change in num, there is also a change in refNum

Last updated