Lesson content
Read, practise, then check your understanding
Operator overloading assigns existing C++ operator syntax to user-defined types. It cannot create new operators or change precedence, associativity, arity, or built-in behavior. At least one operand must be a class or enumeration type.
#include <compare>
class Distance {
int metres_{};
public:
explicit Distance(int metres) : metres_{metres} {}
Distance& operator+=(Distance other) {
metres_ += other.metres_;
return *this;
}
friend Distance operator+(Distance left, Distance right) {
left += right;
return left;
}
auto operator<=>(const Distance&) const = default;
};
Implement a mutating compound operator first, then derive its value-returning binary counterpart. The conventional postfix increment takes a dummy int parameter and returns the previous value, while prefix returns the updated object.
Preserve expectations
+ should not secretly modify its operands, equality should be reflexive and consistent, and ordering should support algorithms. Assignment-like operators are normally members; symmetric binary operators often work best as non-members, possibly friends. operator[] commonly supplies const and non-const overloads.
Operators ::, ., .*, and ?: cannot be overloaded. Overloaded && and || do not provide the built-in short-circuit semantics, so avoid them. Use a named function whenever operator meaning would be ambiguous or domain conventions do not make it obvious.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.