TRT
Sign in
easyFoundationsconcept

When should you pass by pointer, by reference, or by value in C++?

State what each choice copies, what it costs, and the rule for picking between them, including null and reassignment.

TRT practice prompt — not a verified question from a named employer.

The Runtime Theory Team1 min read
Learn it firstMemory addresses and pointersMemory is one long row of numbered bytes. A pointer is a variable that holds one of those numbers, and following it is how every linked structure works.

A strong answer

Passing by value copies the argument into the function's own variable. The function works on the copy, so the caller's variable is safe, and the cost equals the size of the copy: nothing measurable for an int, but a full copy for a large struct or vector.

Passing by pointer copies only an address, 8 bytes on a 64-bit machine, however large the object. The function reaches the caller's object through that address and can change it. A pointer can be null, so the function must check before use, and it can be reassigned to point at a different object later.

A C++ reference is also passed as an address under the hood, but the language treats it as another name for the object: it must be bound when created, cannot be reseated, and cannot legally be null. Passing a large object you only read as const T& avoids the copy while guaranteeing the function won't change it.

The rule follows cost and intent: pass small types such as integers and doubles by value, because copying 8 bytes beats following a pointer; pass large read-only objects by const reference; use a non-const reference or a pointer only when the function is meant to change the caller's object, and a pointer when "no object" is a valid input.

What the interviewer is listening for

  • What is copied in each case, with the 8-byte address cost for pointers and references.
  • Null and reseating as the real differences between pointers and references.
  • A clear choosing rule driven by size, performance, and intent.
  • Awareness that const T& is the default for large read-only inputs.

Common mistakes

  • Saying references are faster than pointers when both pass an address.
  • Claiming a reference can be null or reseated like a pointer.
  • Passing tiny types by reference, which adds indirection for no gain.

This answer walks

Practice follow-ups

  1. 01When should you avoid passing by reference?
  2. 02Can a reference be null?
  3. 03Why is passing a small integer by const reference slower than passing it by value?

Not started

Sign in to save your learning progress.

Sign in to save