C++ for Embedded · Interview question

Does assigning to a reference change what it refers to?

A strong answer

No. Once a reference is bound, it refers to that object for its entire life, assignment through the reference copies a value into the referent, it doesn't rebind the reference. So int& r = a; r = b; does not make r refer to b; it assigns b's value into a (which r aliases). This is a common point of confusion for people coming from pointer thinking, where p = &b does repoint. If you genuinely need something that can refer to different objects over its lifetime, walking a list, a "current selection", you need a pointer, because reseating is exactly the capability a reference gives up.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

References vs Pointers

References are aliases that can't be null and can't be reseated. When to reach for a reference, when you still need a pointer, and why const& is the default way to pass objects.

More References vs Pointers questions

Browse all 472 interview questions