Embercode
✕
Object-Oriented ProgrammingQuick quiz

Invariants

6 questions. Covers Invariants and validation.

Questions 1 to 5 of 6

  1. 1. This setter has a bug. What happens when validate throws for a bad day? ``cpp void set_check_in(int day) { check_in_ = day; validate(day, check_out_); } ``
  2. 2. Which of these is NOT one of the three places the lesson says a rule must be checked?
  3. 3. What does this program print? ``cpp #include <iostream> #include <stdexcept> class Reservation { public: Reservation(int check_in, int check_out) : check_in_{check_in}, check_out_{check_out} { validate(check_in, check_out); } void set_check_in(int day) { validate(day, check_out_); check_in_ = day; } void set_check_out(int day) { validate(check_in_, day); check_out_ = day; } int check_in() const { return check_in_; } int check_out() const { return check_out_; } int nights() const { return check_out_ - check_in_; } private: static void validate(int in, int out) { if (in < 1) throw std::invalid_argument("check-in day must be 1 or later"); if (out <= in) throw std::invalid_argument("check-out must be after check-in"); if (out - in > 30) throw std::invalid_argument("a stay can be at most 30 nights"); } int check_in_; int check_out_; }; int main() { Reservation r{3, 7}; r.set_check_out(20); std::cout << r.nights() << '\n'; try { r.set_check_in(20); } catch (const std::invalid_argument&) { std::cout << "rejected\n"; } std::cout << r.check_in() << '\n'; } ``
  4. 4. The lesson's assert example prints age stored: -5 in one build. Fill in the blank: the assert macro is removed when the ____ macro is defined, as it is in many release builds.

    Type your answer.

  5. 5. Why does the lesson say assert is the wrong tool for checking a user's age?

5 question(s) left on this page.

Typed answers ignore extra spaces and, for most questions, capital letters.