Learning materials
Reference Type Basics
On this page
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
myValueovermyValueRef - Not useful unless passed around as parameters or returned value
- Name after the variable to be bound. e.g. choose
Pitfalls
- confusing ref type with pointer type syntaxes
- declaration without initialization
- trying to reassign value
Examples
// ==== Reference type ====
// ---- correct ----
int a = 10;
int b = 100;
int &myRef1 = a; // initialization, myRef1 is now an alias of a
myRef1 = b; // assignment, it is same as a = b; value of a become 10
int &myRef2 = myRef1; // myRef2 will also bind to a
// ---- wrong ----
int a;
int &alias; // no initialization
int &alias = &a; // alias is not a pointer
int &&alias1 = alias; // there is no ref to ref type!
cout << *alias; // not a pointer, no need of * to dereference