In C++, when would you pass a function argument by value versus by const reference, and why does it matter?
technical-conceptual · Junior level · software-engineering
What the interviewer is really asking
Assesses whether the candidate reasons about copy cost and intent when choosing a parameter-passing style, rather than copying everything by default.
What to say
- State the size-driven default: pass small, cheap-to-copy types like int or a pointer by value, but pass large class types you only need to read by const reference to avoid copying the whole object.
- Explain why const reference matters: the reference avoids the copy while const guarantees the function won't modify the caller's object and lets it bind to temporaries and read-only data.
- Cover the intent angle: pass by non-const reference only when the function deliberately needs to modify the caller's argument, and pass by value when the function takes ownership of the value (a 'sink').
What to avoid
- Saying you should always pass everything by const reference; for a small built-in type like int, copying is as cheap or cheaper and a reference adds an indirection.
- Forgetting const on a read-only reference parameter, which both invites accidental modification and stops it binding to a temporary.
- Confusing pass-by-reference with passing a pointer and dealing with null checks when a reference would be cleaner and can't be null.
Example answers
Strong: If the type is small and cheap to copy, like an int or a pointer, I pass by value because the copy is trivial. For a big object I only need to read, like a std::string or a vector, I pass by const reference so I skip the copy, and the const means I won't modify the caller's object and it can bind to a temporary. I only use a non-const reference when the function is supposed to change the argument.
Weak: I pass everything by const reference because references are faster than copies and it's a good habit. For ints it doesn't really matter so I do the same thing for consistency. If I need to change something I pass a pointer and check it isn't null.