C++ for Embedded · Interview question

Why prefer the member initializer list over assigning members in the constructor body?

A strong answer

The initializer list initializes each member directly, once, before the constructor body runs. Assigning in the body means the member is first default-initialized (or left indeterminate) and then assigned, two operations instead of one, which for non-trivial members is wasteful. More importantly, some members must use the initializer list: const members and reference members can't be assigned after construction, and members that are class types without a default constructor have nowhere to come from except the list. So the initializer list is both more efficient and sometimes the only legal option. One caveat: members initialize in declaration order regardless of list order, so list them in declaration order and watch for dependencies between them.

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

Constructors, Destructors & RAII

Tie setup to object creation and cleanup to scope exit, so you can't forget to release a lock, disable a clock, or re-enable interrupts. The defining C++ idiom for embedded.

More Constructors, Destructors & RAII questions

Browse all 472 interview questions
Why prefer the member initializer list over assigning members in the constructor body? | EmbeddedPrep.io