After this lesson, you will be able to: Use references vs pointers correctly, apply const correctness, and pass parameters efficiently.
References + const are how C++ stays fast without giving up safety. Get them right and your code is a joy to read.
References are pointers that can't be null or rebound.
int x = 5;int y = 10;int* p = &x; // pointer: can be null, can be reboundp = &y; // OKp = nullptr; // OK*p = 20; // would crash if nullint& r = x; // reference: must initialize, cannot rebind// int& r2; // ERROR: must initializer = y; // this ASSIGNS y's value to x; doesn't rebindr = 100; // sets x to 100 (r is still bound to x)// Use reference when: you'll always have a valid object// Use pointer when: optional/nullable, dynamic allocation, or pointer arithmetic
Apply const everywhere you can. It's documentation + compiler-enforced.
// Parameter passing rules:void byValue(int x); // small types (int, double, ptr), pass by valuevoid byConstRef(const std::string& s); // expensive-to-copy + read-only, const refvoid byRef(std::string& s); // expensive-to-copy + mutate, refvoid byPointer(std::string* s); // optional/nullable, pointer// Const member functions: doesn't modify *thisclass User {std::string name_;public:const std::string& name() const { return name_; } // const member fnvoid setName(const std::string& n) { name_ = n; } // non-const member fn};const User alex("Alex");alex.name(); // OK, const fn callable on const obj// alex.setName("x"); // ERROR, non-const fn not callable on const obj
int / float / pointer / small struct (<= 16 bytes): pass by value. std::string / std::vector / custom class (read-only): pass by `const T&`. Same but mutable: pass by `T&`. Optional/nullable: pass by `T*` or `std::optional<T>`. Sink parameter (you'll move-from it): pass by value + `std::move` inside.
Returning references to local variables (dangling reference UB). Skipping `const` everywhere (loses compiler help). Passing big types by value (silent perf hit). Using pointers where a reference would do (extra null-check noise).
Sign in and purchase access to unlock this lesson.