C++ for Embedded · Interview question

What does encapsulation give you over C's struct-plus-functions style?

A strong answer

It moves an invariant from "documented and hoped-for" to "compiler-enforced." In C, a struct's fields are public, so any code can poke them, nothing stops a caller from desynchronizing a ring buffer's head and tail by writing the fields directly, or calling uart_send before uart_init. A class marks that state private, so the only way to change it is through the public methods, which maintain the invariant. The compiler rejects external access at build time. You get a small, deliberate interface and a guarantee that the internal consistency rules can't be violated from outside, which dramatically narrows where a bug could originate. It's the same data and functions as the C version, just with an enforced boundary.

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