Lecture 12
Why Overload Operators?
Operator overloading lets user-defined types use the same syntax as built-in types. Without it,
working with String is verbose:
With overloaded operators, the same code is natural:
Member vs Non-Member Operators
An operator can be a member function or a free (non-member) function:
| Operator | Form | Reason |
|---|---|---|
[], =, (), -> | must be member | language requirement |
<<, >> | must be non-member | left operand is ostream, not your class |
+, ==, !=, < | either | non-member preferred for symmetry |
Member operators receive this as the implicit left operand. Non-member operators take both
operands explicitly. A non-member that needs access to private members is declared a friend:
Subscript Operator (operator[])
Provide both a const and a non-const overload so bracket access works on both mutable and
const String objects:
The non-const version returns a reference so callers can write s[0] = 'H'.
Like std::string, operator[] performs no bounds check. Use at() when you want a guaranteed
exception on out-of-range access.
Equality Operators (operator== and operator!=)
Comparing two strings means checking length and then contents:
std::strcmp (from <cstring>) returns 0 if two C-strings are equal, negative if lhs < rhs,
positive if lhs > rhs.
Stream Output (operator<<)
operator<< must be a non-member — the left operand is std::ostream, not String. Return
std::ostream& to allow chaining (std::cout << a << b):
Concatenation (operator+)
operator+ creates a new String containing both — it does not modify either operand:
std::strcat (from <cstring>) appends the second C-string onto the end of the first.
In-Place Append (operator+=)
operator+= modifies this in place and returns *this:
With operator+= defined, operator+ can delegate to it:
String — Full Declaration Through Lecture 12
Exercises
Q1.
Without running the code, predict what this program prints.
Q2.
Without running the code, predict what this program prints.
Q3.
Each snippet has a bug related to operator overloading. Identify what's wrong.
Q4.
Implement operator< for String that compares two strings lexicographically.
Q5.
Using only the operators defined on String so far (+, ==, <<, []), write a function
is_anagram(const String& a, const String& b) that returns true if the two strings contain
exactly the same characters in any order. You may use a plain int freq[256] = {} array for
character frequency counts.
Practice Problems
- Design an Ordered Stream — Easy
- Custom Sort String — Medium
- Find Players With Zero or One Losses — Medium