← All CPP Flashcard Decks

Operator Overloading & Type Conversions Flashcards

7 cards from real CPP practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.

Read the first 7 Operator Overloading & Type Conversions flashcards as text
  1. What is the correct member function signature for overloading the less-than operator for class T?

    Answer: bool operator<(const T& other) const

    `bool operator<(const T& other) const` is correct — it returns bool, accepts a const reference to avoid copying, and is const-qualified since comparison does not modify the object.

  2. What is a conversion operator in C++?

    Answer: A member function that converts an object to another type

    A conversion operator (e.g., `operator int() const`) is a member function that defines how an object is implicitly or explicitly converted to another type.

  3. Why is it often preferable to implement a symmetric binary operator (like +) as a non-member function?

    Answer: It allows implicit conversions on the left-hand operand as well

    Non-member operators allow the compiler to apply implicit conversions to both operands, including the left-hand side, which member functions cannot support.

  4. For const-correctness, what does a class typically need to provide when overloading operator[]?

    Answer: Both const and non-const versions

    Both a non-const version (returning T&) for modification and a const version (returning const T&) for read-only access are typically needed.

  5. What are user-defined literals in C++?

    Answer: Operators that define custom suffixes for literal values

    User-defined literals let you overload `operator""` with a custom suffix (e.g., `42_km`) to return user-defined types from literal expressions.

  6. What does the 'rule of three' state in C++?

    Answer: If you define a destructor, copy constructor, or copy assignment operator, you should define all three

    If a class manually manages resources requiring a custom destructor, it almost certainly needs a custom copy constructor and copy assignment operator as well.

  7. In C++20, what type does the three-way comparison operator (operator) return?

    Answer: A comparison category such as std::strong_ordering

    operator returns a comparison category type (std::strong_ordering, std::weak_ordering, or std::partial_ordering) that encodes less-than, equal, or greater-than.