C++C++
BeginnerLesson 6 of 18

References, Pointers and const Correctness – C++

Passing by value, by reference and by const reference, plus the basics of pointers.

By default, an argument is copied (pass by value). A reference (&) is another name for the same object: no copy, and changes affect the original.

#include <iostream>
#include <string>

void tausche(int& a, int& b) { int t = a; a = b; b = t; }     // reference: changes the original
void zeige(const std::string& s) { std::cout << s << '\n'; }   // const&: read only, no copy
int verdopple(int x) { return x * 2; }                         // value: cheap to copy

int main() {
    int x = 1, y = 2;
    tausche(x, y);
    std::cout << x << " " << y << '\n';    // 2 1
    zeige("a large text with no copy");
    std::cout << verdopple(21) << '\n';    // 42
}
  • Pass small types (int, double, char, pointers) by value
  • Pass large types (std::string, std::vector, your own classes) by const& when they are only read
  • Output parameters via & – or better, simply return the value
  • With const, you promise the compiler (and readers) not to change something

A pointer stores the address of an object. &x yields the address, *p accesses the object. nullptr means "points to nothing". In modern C++ you rarely need raw pointers – only as a non-owning "view" of objects.

int wert = 10;
int* p = &wert;
*p = 20;
std::cout << wert << " " << *p << '\n';   // 20 20

int* leer = nullptr;
if (leer == nullptr) std::cout << "no target\n";

const int* a = &wert;    // pointer to const int: *a must not be changed
int* const b = &wert;    // const pointer: b must not be redirected
WarningNever return a reference or pointer to a local variable – it is destroyed after the function ends (dangling). A reference must also be initialized immediately and cannot later be redirected to another object.