Concept quiz: C++ foundations and modeling
This quiz checks the main rules of the C++ foundations and modeling sections. Each question names the lesson section it comes from. Read the lessons first, or take the quiz first to find out which ones to read; both work.
How to take it: choose your answer, select “Check answer”, and then read the explanation under every option, not only the one you chose. The wrong options are common mistakes, and each explanation says why it fails. You can change an answer and check it again.
About this quiz.22 questions. Each one links to the lesson it comes from. Fact questions have one answer that follows from the lesson. Judgement questions depend on trade-offs stated in the question; where more than one answer can be defended, the question says so. This is a self-check for your own study, not a test or a certification.
Your answers are saved only in this browser’s local storage, so you can come back to them. Nothing is sent to a server, and nothing is shared between devices or browsers. “Reset this quiz” below removes them, and so does the reset on the “My progress” page.
Show the explained answers
- Right:
struct, with public data members
Right. Astructis for plain data whose members can each take any value independently. There is no combination of values that must never exist, so there is nothing to protect. - Not right:
class, with private members and a getter and a setter for each
A getter and a setter for every field add code and protect nothing, because any value can still be set. Aclasswith private data is for a type with an invariant. - Not right:
class, because astructcannot have member functions or constructors
The premise is false. In C++ the only difference is the default access:structmembers and bases are public until said otherwise,classmembers and bases are private. Either can have member functions and constructors.
Lesson: Classes, objects, and access control: struct or class?
Show the explained answers
- Right: A
const Member¶meter
Right. Aconst T&borrows the object for reading during the call. It is never null, and it does not own. - Right: A
const Member*parameter
Right. A raw pointer observes an object that may be absent (nullptr). In well-designed modern C++, raw pointers and references never own. - Not right: A
std::unique_ptr<Member>parameter
Astd::unique_ptrowns exclusively. Passing one by value transfers ownership to the function. - Not right: A
std::vector<Member>data member
Containers own their elements. The members live inside the vector and are destroyed with it.
Lesson: References, pointers, and ownership: reading ownership from signatures
Show the explained answers
- Right: The
Noticeversion, because only theNoticepart was copied
Right. ANoticeparameter has room for aNoticeand nothing more, so the derived part is sliced off. This compiles without a warning and is not undefined behaviour; it is just not what was intended. Pass polymorphic objects by reference or pointer. - Not right: The
OverdueNoticeversion, becausetext()is virtual
A virtual call runs the version for the object’s real type, but after the copy the real type isNotice. The override would run through aconst Notice&, which refers to the caller’s actual object. - Not right: Nothing: the call does not compile
It compiles. That is what makes slicing a trap: the lesson notes that GCC and Clang give no warning with the site’s warning flags.
Show the explained answers
- Right: Declare the cache
mutable, clear it in every function that changes the real state, and do not assume theconstfunction is safe to call from several threads
Right.constmeans logical constness: callers cannot observe the cache.mutablebrings two obligations: every change must invalidate the cache, and two threads calling theconstfunction can write the cache at the same time, which is a data race. - Not right: Use
const_castonthisinsidetotal_copies()to write the cache
Castingconstaway to modify an object breaks the design’s promises, and is undefined behaviour if the object was definedconst. - Not right: Remove
constfromtotal_copies(), because it writes a data member
Callers holding aconstreference could then no longer ask for the total, although nothing they can observe changes. The interface should express logical constness, not bitwise constness.
Show the explained answers
- Right: The file is closed on every path out of the owning object’s scope, including early returns and exceptions
Right. A local object’s lifetime ends on every path out of its scope, and its destructor runs then. The lesson notes the exception: a program ended abruptly, for example bystd::abortor by an exception that nocatchhandles, is not guaranteed to unwind. - Not right: The file is closed when the program exits, but not earlier
Release happens exactly when the owning object is destroyed, which for a local object is the end of its scope, not the end of the program. - Not right: Nothing extra: callers must still call a close function on every path
Manual release on every path is the problem RAII solves. It works until someone adds a path; the destructor removes the need to remember.
Lesson: RAII and resource management: the destructor does the cleanup
Lesson: Smart pointers: values first
Show the explained answers
- Right: As a plain
Addressdata member
Right. Own by value first. A value needs no pointer, no allocation, and no thought about who deletes it. - Not right: As a
std::unique_ptr<Address>
A smart pointer is for an object that is polymorphic, must outlive its scope, must not move, or is truly shared. None of these applies, so the heap object and the possible null add cost and checks for no benefit. - Not right: As a
std::shared_ptr<Address>
Shared ownership needs a reason: several parts of the program with no single obvious owner. Here the member is the only owner. - Not right: As an
Address*created withnewand deleted in the destructor
Never own with a raw pointer andnew/delete. It also needs hand-written copy and move operations, and every early return or exception becomes a possible leak.
Lesson: Smart pointers: values first
Show the explained answers
- Right:
ais copied, silently
Right.std::moveis only a cast; here it gives aconst Buffer&&. The move constructor takes a non-constBuffer&&and cannot accept it, but the copy constructor, takingconst Buffer&, can. - Not right:
ais moved, and is left empty
Moving changes the source, so a move constructor cannot take aconstobject. Whether anything moves depends on which constructor is chosen, not onstd::moveitself. - Not right: The code does not compile
It compiles, and the lesson notes that GCC and Clang give no warning with the site’s flags. Do not make an objectconstif you intend to move from it.
Show the explained answers
- Right: None of them
Right. This is the Rule of Zero: a class that is not specifically about managing a resource declares none of the five. The generated ones work member by member, and each member manages itself. - Not right: All five, because it holds a resource
The Rule of Five is for a class that manages a resource directly.Sessionholds the connection throughConnectionHandle, which already does that job. - Not right: Only a destructor that closes the connection
ConnectionHandlealready closes it, so a second close would be wrong. Declaring a destructor also stops the move operations from being generated.
Show the explained answers
- Right: Undefined behaviour: the delete goes through a
Record*, and theLoanRecordpart is not properly destroyed
Right. Without a virtual destructor, deleting through a base pointer runs the destructor that the pointer’s type names. The standard calls this undefined behaviour; in the lesson’s example thetitlestring leaks. A class used through base pointers needs a public virtual destructor. - Not right: Nothing goes wrong, because
std::unique_ptralways calls the right destructor
Astd::unique_ptr<Record>deletes through aRecord*; it does not remember the derived type. The lesson’s flawed example is exactly this case. - Not right: The code does not compile until the destructor is made virtual
It compiles. That is why the lesson says a class not designed as a base should not be derived from, and an interface should declare a public virtual destructor.
Lesson: Inheritance and interfaces: why the destructor must be virtual
Show the explained answers
- Right: Two independent choices are tied together in one hierarchy, so classes multiply with each new option; a report that has a formatter and a filter lets each vary on its own
Right. Inheriting only to reuse code couples a class to its base’s implementation and makes independent choices multiply into classes. With composition, the parts can be chosen at run time and tested alone. - Not right: Inheritance is always wrong for reuse in C++, so every base class should be replaced
The lesson says composition is the default for reuse, not that inheritance is always wrong. ItsFormatteris still an interface with several implementations, which is inheritance used well. - Not right: Virtual function calls are too slow for printing reports
Speed is not the problem the lesson describes, and the redesign still calls the formatter through virtual functions.
Lesson: Composition over inheritance: a hierarchy built for reuse
Both vector designs can be defended. The deciding fact is how often lookups by ID happen: a second index makes them fast, but every change must then update both containers and keep them in agreement.
Show the explained answers
- Can be defended: One
std::vector<Member>in joining order, searched linearly by ID
Defensible, and the simplest. The lesson says that for a few hundred members searched occasionally, one vector and a linear search may be the better design. Big-O describes growth, not speed for small data. - Can be defended: A
std::vector<Member>in joining order, plus astd::unordered_mapfrom ID to position in the vector
Defensible if lookups become frequent; this is the lesson’s member index. The cost is a second container that every change must update. The map stores positions, not pointers, because adding to the vector can invalidate pointers into it. - Hard to defend: Only a
std::unordered_mapfrom ID toMember
An unordered map does not keep joining order, which the club needs for its list. - Hard to defend: A
std::setof members sorted by name
Sorted order by name answers neither question: it loses joining order and does not look up by ID.
Both vector designs can be defended. The deciding fact is how often lookups by ID happen: a second index makes them fast, but every change must then update both containers and keep them in agreement.
Show the explained answers
- Right: An interface with virtual functions
Right. Virtual functions fit when the implementation is chosen or changed at run time, such as from configuration or a user’s choice. - Not right: A class template with the rule as a type parameter
A template chooses the implementation when compiling.Checkout<A>andCheckout<B>are unrelated types, so the rule cannot be swapped while the program runs. - Not right: A template, because virtual calls are always too slow
The call-cost difference is real but usually small; it matters for operations called millions of times in a loop. Measure before choosing a template for speed alone.
Show the explained answers
- Right: Return a
std::variantholding either the ID or a reason for the failure
Right. Bad input is an expected failure that the caller handles on the spot, so an error value fits, and the variant carries the reason the kiosk must show. - Not right: Return a
std::optionalholding the IDstd::optionalfits when the caller only needs to know whether it worked. Here the kiosk needs the reason, which an empty optional does not carry. - Not right: Throw an exception
Exceptions fit failures that are rare and that only code far up the call stack can handle. A typo at a kiosk is neither.
Lesson: Testing basics: boundary values
Show the explained answers
- Right: 0 (returned on the due date)
Right. 0 is the edge between on time and late; the fee must be 0. - Right: 1 (the first late day)
Right. The first day that costs money is just past the on-time edge. - Not right: 20
An ordinary value in the middle of the range. It is a fine example, but bugs rarely hide in the middle; they hide at the edges. - Right: 40 (the cap reached exactly)
Right. A<written instead of<=would show here. The lesson tests 39, 40, and 41: each limit, and the values just inside and outside it. - Right: 41 (past the cap)
Right. Just outside the limit: the fee must stay at the cap.
Lesson: Testing basics: boundary values
Show the explained answers
- Right: The member account
Right. Give a responsibility to the object that has the information it needs (information expert). The limit and the blocked flag are facts about the member, and the loan ledger supplies the count. - Not right: The loan desk, the coordinator that handles the request
The coordinator asks the others in the right order and decides the result, but it holds no rules of its own: it decides the order, not the rules. - Not right: The catalog
The catalog knows the library’s copies, not the member’s limit or whether the account is blocked.
Lesson: Objects, classes, and responsibilities: the object that knows
Show the explained answers
- Right: An amount of money, such as $10
Right. $10 is $10; there is no “which $10”. If any part changes, it is a different value. - Not right: A library member
Two members both named “Sam Lee” at the same address are two people. A member has an identity that lasts while their name, address, and balance change, so it is an entity. - Right: An e-mail address that is checked when it is created
Right. The lesson’sEmailAddressis a value object with a rule: it can only be created byparse, which checks the text, so every one in the program is already valid. Two equal addresses are interchangeable. - Not right: “Charge the late fee for a return”
This is an operation that belongs to no single entity or value: a domain service.
Lesson: Entities, value objects, and domain services: three kinds of domain concept
Show the explained answers
- Right: So that passing a copy ID where a member ID is expected, or the arguments the wrong way round, does not compile
Right.MemberIdandCopyIdare unrelated types, and theexplicitconstructor means anintnever silently becomes one. The cost is a few lines per ID type. - Not right: So that the IDs use less memory than an
int
The wrapper holds the same number. The benefit is type checking, not size. - Not right: Because an
intcannot be used as a key instd::map
Anintcan be a map key. A strong ID type needs ordering (the defaultedoperator<=>) to be one too; that is a requirement, not the reason for the type.
The first two options are both associations, and both are defended in the lesson. An ID is the better choice when lifetimes are long or unclear; a pointer is fine when every object’s lifetime is obvious, as in the lesson’s example.
Lesson: Relationships: other designs
Show the explained answers
- Can be defended: An
InstructorId, looked up in a directory when needed
Defensible. Nothing can dangle: if the instructor leaves, the lookup fails and the code must handle it. The cost is a lookup, and a directory that every user of the course must reach. - Can be defended: A
const Instructor*member, with a comment that the instructor must outlive the course
Defensible, and what the lesson’s example does, because every object lives inmainand the lifetimes are obvious. Write the lifetime rule next to every non-owning pointer member. - Hard to defend: A
std::shared_ptr<Instructor>
That changes the meaning: the course now shares ownership, and an instructor who leaves stays in memory while a course still points at them. Shared ownership is rarely right for “knows about”. - Hard to defend: An
Instructorvalue member
A value member is composition: the course would hold its own copy, which dies with it, and changes to the real instructor would not be seen.
The first two options are both associations, and both are defended in the lesson. An ID is the better choice when lifetimes are long or unclear; a pointer is fine when every object’s lifetime is obvious, as in the lesson’s example.
Lesson: Relationships: other designs
Show the explained answers
- Right:
std::optional<DeliveryNote>
Right. For an owned0..1,std::optionalsays in the type that the value may be absent, so every reader must check. - Not right: A plain
std::stringmember, empty when there is no note
A plain member fits1. Using a special “no value”, such as an empty string, for0..1hides the check that readers must make. - Not right:
std::vector<DeliveryNote>
A container fits0..*. It would allow two notes, which the multiplicity forbids, and nothing in the type says so.
Lesson: Multiplicity and object lifecycle: from multiplicity to C++ type
Show the explained answers
- Right: Reject caller mistakes, then check the business rules, then make the change
Right. A bad argument throws before anything changes, and a refusal returns an outcome and changes nothing, so the invariants are still true. The change comes only after every check. - Not right: Make the change, then check the rules, and undo the change if a rule is broken
Between the change and the undo, the invariants are false, and if the undo fails or an exception is thrown, they stay false. Check before changing. - Not right: Check the business rules first, then the arguments, then make the change
The lesson checks arguments first, so a negative amount throwsstd::invalid_argumenteven on a closed account, instead of being reported as a normal refusal.
Lesson: Invariants and class contracts: a basic bank account
Show the explained answers
- Right: So that GCC and Clang warn about each
switchthat does not handle a newly added state
Right. With every state listed,-Wswitch(part of-Wall) reports a missing case. Adefault:would silence that, and the new state would quietly be treated like the others in thedefault. - Not right: Because a
switchover anenum classcannot have adefault:label
It can. The lesson leaves it out on purpose, and adds areturnafter theswitchbecause a badstatic_castcould produce a value outside the enumerators. - Not right: To make the
switchrun faster
Speed is not the reason the lesson gives; the reason is the compiler warning.
Lesson: State diagrams and state machines: from diagram to code
Show the explained answers
- Right: As a
std::stringby value, thenstd::moveit into astd::stringmember
Right. This is a sink parameter. A caller with a temporary pays one move, a caller with a named string pays one copy it would pay anyway (plus a cheap move into the member), and a caller who no longer needs its string can move it in. - Not right: As a
std::string_view, stored in astd::string_viewmemberstd::string_viewis for text the function reads without keeping. Never store a view: it would refer to the caller’s characters, which may be gone later. - Not right: As a
const std::string&, copied into the member
This always copies inside the function, even when the caller passes a temporary that could have been moved.
Your results
This summary helps you decide what to reread. It is not a certification and does not measure professional skill: a quiz checks that you remember and can apply the lessons’ rules, not that you can design a system.
Reset
Removes your saved answers for this quiz from this browser.