OnlineCBT Logo OnlineCBT
C++ · LESSON 4

References vs Pointers in C++

By Ratan Updated: 15 Oct 2026

Understand C++ references (&) as variable aliases vs raw pointers (*).

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Two ways to refer to an existing object

A reference is an alias bound to an object. A pointer is an object that stores an address and can represent “no object” with nullptr. Choose references when a valid object is required, and pointers when optional or reseatable observation is part of the interface.

Observe the difference

#include 
void increment(int& value) { ++value; }
int main() {
    int score{10};
    int& alias = score;
    int* pointer = &score;
    increment(alias);
    *pointer += 4;
    std::cout << score << '\n';
    int other{50};
    pointer = &other;
    alias = other;
    std::cout << score << ' ' << *pointer << '\n';
}

Expected lines: 15 and 50 50. Assigning to alias changes score; it does not rebind the reference to other. Assigning &other to pointer changes the pointer's target without changing score.

Read-only parameters

void print(const std::string& text) accepts a string without copying it and prevents modification through that reference. It is useful for larger read-only values. Passing a small int by value is usually simpler. A const pointer target and a const pointer itself are different: const int* p restricts writes to the target, while int* const p restricts reseating p.

Lifetime still matters

A reference does not keep an arbitrary referred-to object alive indefinitely. Returning a reference or pointer to an automatic local creates a dangling result. A pointer into a vector can become invalid when the vector reallocates. Store and use borrowed access only while its target remains valid.

A reference cannot be validly bound by dereferencing nullptr. Saying “references are never null” is an interface expectation, not permission to create one from an invalid pointer. Use nullptr rather than the integer literal zero to express a null pointer in modern C++.

Exercises

  1. Write swap using two int& parameters. Starting at 3 and 8 should produce 8 and 3.
  2. Can int& r; stand alone as a local declaration? No: it needs a binding initializer.
  3. When would a pointer parameter make sense? For an optional object, with a documented nullptr case.
  4. Explain why the final assignment to alias in the example changes score instead of changing the reference relationship.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat