Logo
Articles Compilers Libraries Books MiniBooklets Assembly C++ Rust Go Linux CPU Others Videos
Advertisement

Article by Ayman Alheraki on April 1 2026 02:15 PM

References in Modern C++

References in Modern C++

A reference is an alias for an existing object. Once a reference is initialized to refer to an object, it cannot be made to refer to another object later.

Basic reference declaration

Here:

  • value is an int,

  • ref is a reference to value,

  • both names refer to the same object.

Modifying through a reference

Because a reference refers to the original object, modifying the reference modifies the object itself.

A reference must be initialized

A reference is not like an ordinary variable that can exist without referring to something. It must be initialized when declared.

This is invalid because the compiler requires the reference to be bound to an object immediately.

A reference cannot be reseated

Once initialized, a reference remains bound to the same object.

This does not make ref refer to b. Instead, it assigns the value of b to the object already referred to by ref, which is a.

References in function parameters

References are extremely important in function interfaces.

This allows a function to modify the caller's object directly.

const references

A const reference allows access to an object without copying it and without allowing modification.

This is one of the most common and important patterns in Modern C++.

Reference lifetime caution

A reference must refer to a valid object. If the referred object dies and the reference is still used, the program has a dangling reference.

The local variable is destroyed when the function ends, so the returned reference becomes invalid.

Advertisements

Responsive Counter
General Counter
1195539
Daily Counter
2590