C++ for Embedded · Interview question

Why mark a method const, and what does it guarantee?

A strong answer

A const method promises not to modify the object's observable state, the compiler enforces this by making this a pointer-to-const inside the method, so any attempt to write a data member is a compile error. Two payoffs: it documents and guarantees that a query (like empty(), size(), peek()) is side-effect-free, and it's the only kind of method you can call on a const object or through a const reference. If you forget const on your query methods, any code holding a const& to your object can't call them, and that friction propagates through the whole API. So const-correctness is something you design in from the start: mark every non-mutating method const. (The subtlety: const protects the object's own members, not what a member pointer points at, for that you'd also need the pointee to be const.)

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

Classes & Encapsulation

Bundle data with the code that operates on it, and hide the internals behind a clean interface: the C struct-plus-functions pattern, made safe by the compiler.

More Classes & Encapsulation questions

Browse all 472 interview questions