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

What to avoid

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.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.