12. References – Modern C++ for Absolute Beginners: A Friendly Introduction to C++ Programming Language and C++11 to C++20 Standards

© Slobodan Dmitrović 2020
S. DmitrovićModern C++ for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-6047-0_12

12. References

Slobodan Dmitrović1 
(1)
Belgrade, Serbia
 
Another (somewhat) similar concept is a reference type. A reference type is an alias to an existing object in memory. References must be initialized. We describe a reference type as type_name followed by an ampersand &. Example:
int main()
{
    int x = 123;
    int& y = x;
}
Now we have two different names that refer to the same int object in memory. If we assign a different value to either one of them, they both change as we have one object in memory, but we are using two different names:
int main()
{
    int x = 123;
    int& y = x;
    x = 456;
    // both x and y now hold the value of 456
    y = 789;
    // both x and y now hold the value of 789
}
Another concept is a const-reference, which is a read-only alias to some object. Example:
int main()
{
    int x = 123;
    const int& y = x; // const reference
    x = 456;
    // both x and y now hold the value of 456
}

We will discuss references and const-reference in more detail when we learn about functions and function parameters. For now, let us assume they are an alias, a different name for an existing object.

It is important not to confuse the use of * in a pointer type declaration such as int* p; and the use of * when dereferencing a pointer such as *p = 456. Although the same star character, it is used in two different contexts.

It is important not to confuse the use of ampersand & in reference type declaration such as int& y = x; and the use of ampersand as an address-of operator int* p = &x.s The same literal symbol is used for two different things.