C++ Reference Introduction

Introduction

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 
} 

Const-reference

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 
} 

For now, let us assume references 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.

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.




PreviousNext

Related