Reference Type Basics

TR;DR

  • Ampersand (&) after type to make a derived type

  • Works like an alias to another variable

  • Must be initialized

  • Will never be reassigned

  • Later access/modification will only affect the variable bound to it rather than the reference itself

Overview

Reference type is employed to provide an alias to another variable. There are both lvalue references and rvalue references but only lvalue references are discussed in this document.

Reference type is not useful at all when they are not passed around as parameters or returned value. This document is only for learning purpose and most code snippets are not practical.

  • A derived type to alias other types (including pointer type).

  • & symbol after type to make a derived type

  • Syntax BaseType &name = lvalue

    • lvalue only!

    • Must be initialized!

    • Later access/modification will only affect the variable bound to it

  • Misc. hints

    • Name after the variable to be bound. e.g. choose myValue over myValueRef

    • Not useful unless passed around as parameters or returned value

Pitfalls

  • confusing ref type with pointer type syntaxes

  • declaration without initialization

  • trying to reassign value

Examples

 1// ==== Reference type ====
 2
 3// ---- correct ----
 4int a = 10;
 5int b = 100;
 6
 7
 8int &myRef1 = a; // initialization, myRef1 is now an alias of a
 9myRef1 = b; // assignment, it is same as a = b; value of a become 10
10int &myRef2 = myRef1;  // myRef2 will also bind to a
11
12// ---- wrong ----
13int a;
14int &alias;  // no initialization
15
16int &alias = &a;  // alias is not a pointer
17
18int &&alias1 = alias;  // there is no ref to ref type!
19
20cout << *alias;  // not a pointer, no need of * to dereference