Skip to content

Concept quiz: C++ foundations and modeling

Difficulty: Intermediate

Key concepts

  • concept quiz
  • self-check
  • ownership
  • value semantics
  • invariants
  • relationships

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.

Question 1 of 22FactA type holds an ISBN and a title. Any ISBN can go with any title, and there is no rule linking them. Following this site’s convention, which keyword fits?

Choose one answer.

Show the explained answers
  • Right: struct, with public data members
    Right. A struct is 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. A class with private data is for a type with an invariant.
  • Not right: class, because a struct cannot have member functions or constructors
    The premise is false. In C++ the only difference is the default access: struct members and bases are public until said otherwise, class members and bases are private. Either can have member functions and constructors.

Lesson: Classes, objects, and access control: struct or class?

Question 2 of 22FactFollowing the convention on this site, which of these only observe an object, without owning it? Choose all that apply.

Choose all that apply.

Show the explained answers
  • Right: A const Member& parameter
    Right. A const 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
    A std::unique_ptr owns 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

Question 3 of 22FactA function takes a Notice by value. A caller passes an OverdueNotice, which derives from Notice and overrides the virtual function text(). What does text() return inside the function?

Choose one answer.

Show the explained answers
  • Right: The Notice version, because only the Notice part was copied
    Right. A Notice parameter has room for a Notice and 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 OverdueNotice version, because text() is virtual
    A virtual call runs the version for the object’s real type, but after the copy the real type is Notice. The override would run through a const 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.

Lesson: Value semantics and reference semantics: slicing

Question 4 of 22FactA const member function total_copies() caches the total it computes, so the second call is faster. How does the lesson say to write the cache?

Choose one answer.

Show the explained answers
  • Right: Declare the cache mutable, clear it in every function that changes the real state, and do not assume the const function is safe to call from several threads
    Right. const means logical constness: callers cannot observe the cache. mutable brings two obligations: every change must invalidate the cache, and two threads calling the const function can write the cache at the same time, which is a data race.
  • Not right: Use const_cast on this inside total_copies() to write the cache
    Casting const away to modify an object breaks the design’s promises, and is undefined behaviour if the object was defined const.
  • Not right: Remove const from total_copies(), because it writes a data member
    Callers holding a const reference could then no longer ask for the total, although nothing they can observe changes. The interface should express logical constness, not bitwise constness.

Lesson: const correctness: logical constness and mutable

Question 5 of 22FactA class acquires a file handle in its constructor and closes it in its destructor. What does this guarantee?

Choose one answer.

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 by std::abort or by an exception that no catch handles, 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

Question 6 of 22FactA Member owns one Address. The address is small, is not polymorphic, is not shared, and nothing else holds a pointer to it. How should Member hold it?

Choose one answer.

Show the explained answers
  • Right: As a plain Address data 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 with new and deleted in the destructor
    Never own with a raw pointer and new/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

Question 7 of 22FactCode calls Buffer b = std::move(a); where a was declared const Buffer a = ...;. Buffer has both a copy constructor and a move constructor. What happens?

Choose one answer.

Show the explained answers
  • Right: a is copied, silently
    Right. std::move is only a cast; here it gives a const Buffer&&. The move constructor takes a non-const Buffer&& and cannot accept it, but the copy constructor, taking const Buffer&, can.
  • Not right: a is moved, and is left empty
    Moving changes the source, so a move constructor cannot take a const object. Whether anything moves depends on which constructor is chosen, not on std::move itself.
  • 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 object const if you intend to move from it.

Lesson: Copy and move semantics: std::move is only a cast

Question 8 of 22FactA class Session has two data members: a std::string and a ConnectionHandle, an RAII class that already manages one connection correctly. Which of the five special member functions should Session declare?

Choose one answer.

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. Session holds the connection through ConnectionHandle, which already does that job.
  • Not right: Only a destructor that closes the connection
    ConnectionHandle already closes it, so a second close would be wrong. Declaring a destructor also stops the move operations from being generated.

Lesson: Rule of Zero, Rule of Five: the Rule of Zero

Question 9 of 22FactA std::unique_ptr<Record> holds a LoanRecord, which derives from Record. Record has a public destructor that is not virtual. What happens when the pointer is destroyed?

Choose one answer.

Show the explained answers
  • Right: Undefined behaviour: the delete goes through a Record*, and the LoanRecord part 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 the title string leaks. A class used through base pointers needs a public virtual destructor.
  • Not right: Nothing goes wrong, because std::unique_ptr always calls the right destructor
    A std::unique_ptr<Record> deletes through a Record*; 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

Question 10 of 22FactA report base class has subclasses that each fix two things: the format (CSV or HTML) and the selection (overdue loans or all loans). Why does the composition lesson redesign it?

Choose one answer.

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. Its Formatter is 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

Question 11 of 22JudgementA small club has about 200 members. It lists them in the order they joined, and looks one up by ID a few times a day. Which container design fits?

Choose one answer. This is a judgement question: more than one answer can be defended.

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 a std::unordered_map from 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_map from ID to Member
    An unordered map does not keep joining order, which the club needs for its list.
  • Hard to defend: A std::set of 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.

Lesson: Containers and complexity: choosing a container

Question 12 of 22FactA checkout applies a pricing rule that the shop manager chooses from a settings screen while the program runs. Which form of polymorphism does the lesson recommend?

Choose one answer.

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> and Checkout<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.

Lesson: Templates and polymorphism: when to use which

Question 13 of 22FactA self-service kiosk parses a member ID typed by a member. Bad input is common, and the kiosk must tell the member why the ID was refused. How should the parser report failure?

Choose one answer.

Show the explained answers
  • Right: Return a std::variant holding 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::optional holding the ID
    std::optional fits 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: Errors, exceptions, and contracts: choosing a style

Question 14 of 22FactA late fee is 25 cents a day, capped at 1000 cents, so the cap is reached at exactly 40 days late. Which numbers of days late are boundary values worth a test? Choose all that apply.

Choose all that apply.

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

Question 15 of 22FactIn the lending example, the rule "may this member borrow another copy?" depends on the member’s limit and whether the account is blocked, given how many loans they have now. Which object should answer it?

Choose one answer.

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

Question 16 of 22FactWhich of these are value objects, defined only by their values? Ask: if two have exactly the same attributes, are they the same thing? Choose all that apply.

Choose all that apply.

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’s EmailAddress is a value object with a rule: it can only be created by parse, 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

Question 17 of 22FactWhy give member IDs and copy IDs their own small types, each with an explicit constructor, instead of using int for both?

Choose one answer.

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. MemberId and CopyId are unrelated types, and the explicit constructor means an int never 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 int cannot be used as a key in std::map
    An int can be a map key. A strong ID type needs ordering (the defaulted operator<=>) to be one too; that is a requirement, not the reason for the type.

Lesson: Identity and equality: strong ID types

Question 18 of 22JudgementA course refers to its lead instructor. The instructor exists independently and teaches other courses too; the course does not own them. How should Course hold the instructor?

Choose one answer. This is a judgement question: more than one answer can be defended.

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 in main and 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 Instructor value 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

Question 19 of 22FactAn order may have one delivery note, or none (multiplicity 0..1). The order owns the note. Which C++ type says this in the type itself?

Choose one answer.

Show the explained answers
  • Right: std::optional<DeliveryNote>
    Right. For an owned 0..1, std::optional says in the type that the value may be absent, so every reader must check.
  • Not right: A plain std::string member, empty when there is no note
    A plain member fits 1. Using a special “no value”, such as an empty string, for 0..1 hides the check that readers must make.
  • Not right: std::vector<DeliveryNote>
    A container fits 0..*. 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

Question 20 of 22FactA bank account’s withdraw must keep the account’s invariants true even when it refuses. In which order does the lesson’s withdraw work?

Choose one answer.

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 throws std::invalid_argument even on a closed account, instead of being reported as a normal refusal.

Lesson: Invariants and class contracts: a basic bank account

Question 21 of 22FactA loan’s event functions each switch over its enum class state. Why does the lesson leave out a default: label?

Choose one answer.

Show the explained answers
  • Right: So that GCC and Clang warn about each switch that does not handle a newly added state
    Right. With every state listed, -Wswitch (part of -Wall) reports a missing case. A default: would silence that, and the new state would quietly be treated like the others in the default.
  • Not right: Because a switch over an enum class cannot have a default: label
    It can. The lesson leaves it out on purpose, and adds a return after the switch because a bad static_cast could produce a value outside the enumerators.
  • Not right: To make the switch run 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

Question 22 of 22FactA Member constructor keeps the member’s name in a data member. How should it take the name?

Choose one answer.

Show the explained answers
  • Right: As a std::string by value, then std::move it into a std::string member
    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 a std::string_view member
    std::string_view is 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.

Lesson: Designing member functions: parameters