References

Creating an Array of References

Is it possible to create an array of references in C++?

3D character art

Creating an array of references in C++ is not directly possible. This is because references must be initialized when they are created and cannot be reseated (made to refer to a different object) later. However, there are a few workarounds that can achieve similar functionality.

Using std::reference_wrapper

The most common and recommended approach is to use std::reference_wrapper from the <functional> header. This class template wraps a reference in a copyable, assignable object:

#include <array>
#include <functional>
#include <iostream>

int main() {
  int a{1}, b{2}, c{3};

  std::array<
    std::reference_wrapper<int>, 3
  > refArray{a, b, c};

  for (auto& ref : refArray) {
    std::cout << ref << ' ';
    ref.get()++;  // Modify the original values
  }
  std::cout << '\n';

  std::cout << "a: " << a
    << ", b: " << b
    << ", c: " << c << '\n';
}
1 2 3
a: 2, b: 3, c: 4

In this example, we create an array of std::reference_wrapper<int>. We can access and modify the original values through this array.

Using Pointers

Another approach is to use an array of pointers. While not exactly the same as references, pointers can achieve similar functionality:

#include <array>
#include <iostream>

int main() {
  int a{1}, b{2}, c{3};

  std::array<int*, 3> ptrArray{&a, &b, &c};

  for (auto ptr : ptrArray) {
    std::cout << *ptr << ' ';
    (*ptr)++;
  }
  std::cout << '\n';

  std::cout << "a: " << a
    << ", b: " << b
    << ", c: " << c << '\n';
}
1 2 3
a: 2, b: 3, c: 4

This approach uses pointers instead of references, but achieves a similar result.

Remember, while these methods allow you to create collections of references or reference-like objects, they each have their own implications for syntax and semantics. The std::reference_wrapper approach is generally preferred as it more closely mimics the behavior of actual references.

Answers to questions are automatically generated and may not have been reviewed.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

View Course
Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved