What Are References

beginner c++11 memory

Related: Why Use References and What Are Pointers

References are aliases or “other names” for variables in your program. Because references are simply new names for existing variables C++ treats them exactly as if they were those variables when compiling your code. That means math operations directly apply to the reference as normal and assignment assigns to the reference as you might expect. Functions can also accept references to variables. When a function accepts a reference it’s simply a new name for the variable that’s being passed in. Here’s some examples:

#include <iostream>

void square(int& i) {
  i = i * i;
}

int main() {
  int i = 0;
  // iAlias is another name for the variable "i"
  int& iAlias = i;

  iAlias = iAlias + 2;
  std::cout << i << "\n";

  iAlias = iAlias * 6;
  std::cout << i << "\n";

  square(iAlias);
  std::cout << i << "\n";

  iAlias = 42; 
  std::cout << i << "\n";
}
2
12
144
42

The syntax for a reference is quite simple. You take the type of the variable (such as int) and you add an ampersand (&) after that type such as with (int&). When we do this we have an “int reference” which is a single type, not two things. You can of course have a constant (const) reference, which is only for reading data, not writing data, but nonetheless is used very frequently across C++.

#include <iostream>

void square(int& i) {
  i = i * i;
}

void print_int(const int& i) {
  std::cout << i << "\n";
}

int main() {
  int i = 0;
  // iAlias is another name for the variable "i"
  int& iAlias = i;

  iAlias = iAlias + 2;
  print_int(i);

  iAlias = iAlias * 6;
  print_int(i);

  square(iAlias);
  print_int(i);

  iAlias = 42; 
  print_int(i);
}
2
12
144
42

You can of course have references to objects:

#include <iostream>

struct Point {
  int x, y, z;
};

// See https://cppbyexample.com/print.html for a better example
void print_point(const Point& p) {
  std::cout << p.x << ", " << p.y << ", " << p.z << "\n";
}

int main() {
  Point p{1, 2, 3};
  Point& pointAlias = p;

  pointAlias.x += 2;
  print_point(p);

  pointAlias.y *= 6;
  print_point(p);

  pointAlias.z = 42;
  print_point(p);
}
3, 2, 3
3, 12, 3
3, 12, 42

You Can’t Change What a Reference Points To

Because assignment to a reference is the same as assigning to the variable it refers to you can’t change what a reference points to. In C++, a variable that references to another variable but can change what it points to is called a pointer. For examples of pointers and how to use them, check out What is a Pointer.


For more C++ By Example, click here.