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