Quiz 3 — Answers¶
Q1 — B, before the body runs. A constructor's job is to bring an object into a valid state, so every member must be fully constructed before the body's first line executes. The body is for work that needs a completed object, not for building members.
Q2 —
The member engine_ is constructed before the Car body runs (so "engine on" precedes
"car on"), and destroyed after it, when the Car is destroyed — so "car off" precedes
"engine off". Construction and destruction are mirror images.
Q3 — False. A destructor runs automatically when an object's lifetime ends — on scope
exit, on delete, or during stack unwinding. Calling it by hand, and also letting it run
automatically, is how the same resource gets released twice.
Q4 — A, B, C. A member with no default constructor (A), a reference or const member
(B), and avoiding a default-construct-then-assign (C) are all reasons to use the list. D is
false: the list's order does not change anything — members are initialised in declaration
order, whatever order the list is written in.
Q5 — 5 6.
Members are initialised in declaration order: a_ first (with 5), then b_ (with
a_ + 1 = 6) — even though the initialiser list names b_ first. This code emits GCC's
-Wreorder warning precisely because the list is misleading. The warning is the lesson:
write the list in declaration order.
Q6 — A delegating constructor calls another constructor of the same class from its initialiser list, so the real initialisation logic lives in one place. It avoids copying that logic into each constructor, where the copies drift apart over time.
Q7 — Two messages: the delegating constructor's own body runs, and the target constructor's body runs too (the target runs first, as part of initialising the object). Delegation uses another constructor, it does not replace it.
Q8 —
Now value_ is initialised directly rather than left indeterminate and then assigned. For
an int the difference is small; for a class-typed member it is the difference between one
construction and (default construction + assignment).
Q9 —
c is dropped before b because objects in a block are destroyed in reverse order of
construction. a is destroyed last, at the end of main.
Q10 — The buffer should be released in the destructor, because the destructor runs
on every exit path — normal return, early return, or a thrown exception unwinding the
stack — without the caller doing anything. If instead you required an explicit close(),
every caller would have to remember it on every path, and one forgotten path leaks. The
constructor acquires, the destructor releases: the lifetime of the object is the lifetime
of the resource.
Marking. One point per question (Q4 all-or-nothing). Then read Marking Yourself.