Embercode
✕
Object-Oriented ProgrammingQuick quiz

Factory and enums

8 questions. Covers Enums with fields.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``cpp #include <iomanip> #include <iostream> class Temperature { public: static Temperature from_celsius(double c) { return Temperature{c}; } static Temperature from_fahrenheit(double f) { return Temperature{(f - 32.0) * 5.0 / 9.0}; } double celsius() const { return celsius_; } private: explicit Temperature(double c) : celsius_(c) {} double celsius_; }; int main() { auto a = Temperature::from_fahrenheit(212.0); auto b = Temperature::from_celsius(-5.5); std::cout << std::fixed << std::setprecision(1); std::cout << a.celsius() << ' ' << b.celsius() << '\n'; } ``
  2. 2. What does this program print? ``cpp #include <iostream> enum class Coin { penny, nickel, dime, quarter }; constexpr int cents(Coin c) { switch (c) { case Coin::penny: return 1; case Coin::nickel: return 5; case Coin::dime: return 10; case Coin::quarter: return 25; } return 0; } int main() { int total = 0; for (Coin c : {Coin::dime, Coin::quarter, Coin::penny}) { total += cents(c); } std::cout << total << ' ' << static_cast<int>(Coin::quarter) << '\n'; } ``
  3. 3. Why is the Temperature constructor private in the factory example?
  4. 4. Which two words, written at the start of a C++ enum, make its names scoped, so the value must be written Coin::dime and not dime?

    Type your answer.

  5. 5. What is the bug in this builder? ``cpp class Builder { public: void port(int value) { port_ = value; } void tls(bool value) { tls_ = value; } private: int port_ = 8080; bool tls_ = false; }; int main() { Builder b; b.port(443).tls(true); } ``

5 question(s) left on this page.

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