Which operators you can overload in C++ is a fixed list, and the rules about them are strict. Overloading lets your own types behave like the built-in ones, so a Duration class can be added, compared and printed with the operators that you already know. The technique is powerful and easy to abuse, and the discipline that keeps it sane is a simple rule. Overload an operator only when its meaning for your type is obvious.
The previous lesson in this module covered "What Does Moving an Object Mean?", and this lesson is the last one in the Copy, Move and Special Members module.
The operators you may overload
C++ allows you to overload most of the operators. The ones that you cannot are the ones that the language needs for itself.
the operator can it be overloaded
-------------------------------------- --------------------------------
. :: .* -> sizeof typeid no
alignof ?: no
= it must be a member function
() it must be a member function
[] -> the conversion operators they must be members
& * they must be members if you
overload new or delete
++ -- they must be members
And the comparison operators are a special case in C++20, because of the spaceship relation. In C++17 you can overload them freely.
Everything else is available. The arithmetic operators, the comparison operators, the stream operators, the subscript operator and the call operator.
A first overload: adding two values
An operator overload is a function with a special name. The parameters decide which types take part.
#include <iostream>
class Duration {
public:
explicit Duration(int minutes) : minutes_(minutes) {}
int minutes() const { return minutes_; }
private:
int minutes_;
};
Duration operator+(const Duration& left, const Duration& right) {
return Duration(left.minutes() + right.minutes());
}
std::ostream& operator<<(std::ostream& stream, const Duration& value) {
stream << value.minutes() << " min";
return stream;
}
int main() {
Duration first(45);
Duration second(30);
Duration total = first + second;
std::cout << "first: " << first << '\n';
std::cout << "total: " << total << '\n';
return 0;
}The output shows the custom type printing itself with the stream operator.
first: 45 min
total: 75 minMember or free function
An overload can be a member function or a free function, and the choice is mostly about which arguments should be converted implicitly. A member overload has access to the private members and it takes the left-hand operand as this. A free overload treats both operands equally, and it is the right choice for the symmetric operations.
And the rule of thumb is this. If the operation is symmetric, such as an addition, then write it as a free function. If it modifies the left-hand operand, such as +=, then write it as a member.
#include <iostream>
class Duration {
public:
explicit Duration(int minutes) : minutes_(minutes) {}
int minutes() const { return minutes_; }
Duration& operator+=(const Duration& other) {
minutes_ += other.minutes();
return *this;
}
private:
int minutes_;
};
Duration operator+(const Duration& left, const Duration& right) {
Duration result(left.minutes() + right.minutes());
return result;
}
int main() {
Duration first(45);
Duration second(30);
first += second;
std::cout << "after +=: " << first.minutes() << " minutes\n";
Duration third = first + second;
std::cout << "after +: " << third.minutes() << " minutes\n";
return 0;
}The output shows the member operator modifying in place and the free operator producing a new value.
after +=: 75 minutes
after +: 105 minutesOverloading the stream operators
The operators << and >> are the most commonly overloaded ones, because they are how a type is printed and read. The pattern is fixed. The left-hand parameter is the stream, taken by reference. The right-hand parameter is your type, usually taken by a const reference for the output. And the return type is the stream reference.
#include <iostream>
#include <sstream>
#include <string>
class Coordinates {
public:
Coordinates(int x, int y) : x_(x), y_(y) {}
int x() const { return x_; }
int y() const { return y_; }
private:
int x_;
int y_;
};
std::ostream& operator<<(std::ostream& stream, const Coordinates& point) {
stream << '(' << point.x() << ", " << point.y() << ')';
return stream;
}
std::istream& operator>>(std::istream& stream, Coordinates& point) {
int x = 0;
int y = 0;
stream >> x >> y;
if (stream) {
point = Coordinates(x, y);
}
return stream;
}
int main() {
Coordinates point(12, 34);
std::cout << "point: " << point << '\n';
Coordinates read_in(0, 0);
std::istringstream input("56 78");
input >> read_in;
std::cout << "read: " << read_in << '\n';
return 0;
}The output shows both directions working.
point: (12, 34)
read: (56, 78)The rules that keep overloads sane
- Do not overload an operator whose meaning is unclear. What would
operator==mean for your type? If the answer is not obvious, then do not define it. - Keep the parameters and the return type consistent with the built-in operator. The result of
a + bshould be something that can be added to anothera. - Do not break the symmetry of the built-in behaviour. If
a == bis true thenb == ahas to be true as well. - Do not overload
&&,||or the comma operator. They lose their short-circuit and their sequencing behaviour, and that surprises everybody. - Return
*thisby reference from the compound assignment operators, so that they can be chained. - Mark the read-only member overloads as
const, so that they can be called on const objects.
A worked example with comparison
Overloading the comparison operators lets your type work with the standard algorithms and with std::sort.
#include <algorithm>
#include <iostream>
#include <vector>
class Reading {
public:
Reading(const std::string& label, int value) : label_(label), value_(value) {}
const std::string& label() const { return label_; }
int value() const { return value_; }
private:
std::string label_;
int value_;
};
bool operator<(const Reading& left, const Reading& right) {
return left.value() < right.value();
}
std::ostream& operator<<(std::ostream& stream, const Reading& reading) {
stream << reading.label() << '=' << reading.value();
return stream;
}
int main() {
std::vector<Reading> readings = {
Reading{"oil", 42}, Reading{"coolant", 91}, Reading{"battery", 12}
};
std::sort(readings.begin(), readings.end());
for (const Reading& reading : readings) {
std::cout << reading << ' ';
}
std::cout << '\n';
return 0;
}The output shows the readings sorted by value.
battery=12 oil=42 coolant=91And because operator< is defined, std::sort works on the vector without knowing anything about the type.
Quick reference
- Most operators can be overloaded, and the dot, the scope resolution, sizeof and typeid cannot.
- The assignment, the call, the subscript, the arrow, the increment and the decrement must be member functions.
- Write the symmetric operations as free functions and the modifying operations as members.
operator<<takes the stream by reference and returns it, so that the calls chain.- Never overload
&&,||or the comma operator. - Keep the semantics of the built-in operator, or you will confuse every reader.
Try it yourself: write a Duration class that holds a number of minutes, and then overload the plus operator, the plus-and-equal operator and the stream operator so that it prints as "45 min". Add a comparison operator and put a list of durations into a vector and sort it. Finally, try overloading the logical and operator and see how the short-circuit behaviour changes.