Quiz 2 — Answers¶
Q1 — B, private. A class defaults to private; a struct defaults to public.
That is the only difference between them in C++. The choice is a convention: use class
when you want the compiler to help you keep data hidden.
Q2 — True. Member functions are the same instructions for every object; only the data differs. That is why a member function has an implicit parameter — the object it was called on.
Q3 — A, B, C. Keeping fields consistent (A), rejecting impossible values (B) and hiding a helper that callers should not depend on (C) are all real reasons. "Shorter to type" (D) is not a design reason — public data is usually shorter to type, which is exactly the temptation.
Q4 — 2 1.
Each Counter owns its own value_. The two increments on a affect only a; the one
increment on b affects only b. If both printed 3 you would be looking at shared
(static) state instead of per-object state.
Q5 — this is a pointer to the object the member function was called on. Inside
a.increment(), this points at a; inside b.increment(), at b. It is how one copy
of the code operates on whichever object was used.
Q6 — A member function that only reads the object does not need to modify it, so it
should be marked const. Omitting it means the function cannot be called on a const
object or through a const reference. The concrete failure is exactly Q8's: report
takes const Sensor& and cannot call celsius(), even though celsius() changes nothing.
Marking the accessor const is always safe and never costs anything.
Q7 — A. The public member functions are the interface — the promise the class makes
to its callers. The private members are the implementation detail that may change freely.
An interface is what callers may depend on; that is why area() being public and
const-correct matters beyond convenience.
Q8 — Add const to the accessor:
The error is a promise violation: report received a const Sensor&, so it may only call
members that promise not to modify the object. A read-only accessor always qualifies.
Q9 — 0 then 1.
Box starts closed (the constructor initialises open_), so the first check prints 0;
open() sets the flag and the second check prints 1. This is the shape of every
encapsulated type: private state, and public operations that move it through a small set of
valid states.
Q10 — A reasonable interface: Item(std::string name, double unitPrice, int quantity),
name() const, unitPrice() const, quantity() const, void setQuantity(int),
double lineTotal() const. One invariant: quantity is never negative. The operation
that enforces it is setQuantity (and the constructor), which rejects a negative value.
lineTotal() is a derived value, not stored, so it can never disagree with the quantity.
Marking. One point per question (Q3 and Q6 all-or-nothing). Then read Marking Yourself.