Embercode
✕
Object-Oriented ProgrammingQuick quiz

Immutable and equality

8 questions. Covers Operator overloading and equals.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``cpp #include <iostream> #include <string> #include <utility> class Name { public: explicit Name(std::string text) : text_{std::move(text)} {} bool operator==(const Name& other) const { return text_ == other.text_; } private: std::string text_; }; int main() { std::cout << (Name{"Asha"} != Name{"Ravi"}) << "\n"; } ``
  2. 2. What does bool operator==(const Point& other) const = default; compare?
  3. 3. The compiler rejects this program. What is the reason? ``cpp #include <string> #include <utility> class Money { public: Money(std::string currency, long cents) : currency_{std::move(currency)}, cents_{cents} {} long cents() { return cents_; } private: std::string currency_; long cents_; }; int main() { const Money price{"USD", 1250}; return static_cast<int>(price.cents()); } ``
  4. 4. True or false: two equal objects must always have equal hashes.
  5. 5. A set stores both Point{1, 2} and Point{1, 5}, because operator== compares only x but the hash uses x and y. Which one-line change makes the set keep only one of them?

5 question(s) left on this page.