www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C++ Tutorial - Lesson 13: References

References

by John Kopp

Support this site at no cost to you

References
Good references are required to get a job, loan or possibly even a date. You should never lie about references on your resume because they might be checked. What does this have to do with C++? :-? Nothing, but I can't help but create bad puns, and it gave me an opportunity to use the "puzzle mouth" emoticon. In C++, a reference is an alias to a variable. The real usefulness of references is when they are used to pass values into functions. They provide a way to return values from the function, as will be shown in the next lesson. For now, we'll examine how to create and use references.

A reference is an alias to an object. Here's some code that shows how to create a reference.

int val;    // Declares an integer
int &rVal = val;
        // Declares a reference to the integer object val

Notice the use of the "&" before the reference name. In this context, the "&" is called the reference operator. It indicates that rVal is a reference rather than an ordinary object. In earlier lessons, the "&" was used to obtain an address of an object. In that context, the "&" was called the address of operator. The address of operator is used to obtain an address, typically, to initialize a pointer. Here's an example.

int val;    // Declares an integer
int *pal = &val;
        // Declares a pointer and initializes it to the address of val.

A reference is not a unique object. It is merely an alias or synonym for another object. The reference identifier (name) may be used anywhere the referred identifier may be used. Any changes to the reference also apply to the original object. Changes to the original object are also seen through the reference.


#include <iostream>
using namespace std;

int main()
{

    int val = 1;
    int &rVal = val;

    cout << "val is " << val << endl;
    cout << "rVal is " << rVal << endl;

    cout << "Setting val to 2" << endl;
    val = 2;

    cout << "val is " << val << endl;
    cout << "rVal is " << rVal << endl;

    cout << "Setting rVal to 3" << endl;
    rVal = 3;

    cout << "val is " << val << endl;
    cout << "rVal is " << rVal << endl;

    return 0;
}


Previous Page       Next Page