Understanding Reference and Pointer Types

When to Use Pointers over References

In what situations should I use pointers instead of references in C++?

Abstract art representing computer programming

While references are generally preferred in modern C++, there are still situations where pointers are necessary or more appropriate:

  1. When you need to represent the absence of a value. A pointer can be null, while a reference must always refer to an object.
  2. When you need to change what a pointer points to. References cannot be reassigned after initialization.
  3. When you need to do arithmetic on the address. Pointer arithmetic is not possible with references.
  4. When interfacing with legacy code that uses pointers.

Here's an example where a pointer is used to represent the absence of a value:

#include <iostream>

void Print(const int* ptr) {
  if (ptr) {
    std::cout << "Value: " << *ptr << "\n";
  } else {
    std::cout << "Null pointer\n";
  }
}

int main() {
  int x = 10;
  int* ptr1 = &x;
  int* ptr2 = nullptr;

  Print(ptr1);
  Print(ptr2);
}
Value: 10
Null pointer

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

A computer programmer
Part of the course:

Professional C++

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

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% 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.

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