C++ Beginner · Lesson 18 of 22
Operator overloading
Giving your types +, ==, and << with clear, predictable meaning.
Estimated time · 45–75 min
Learning goals
What you will understand
- Explain operator overloading in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
Operator overloading lets your own types use the built-in operators: a Vec2 can support +, a Pose can support ==, and any type can support << for printing. Overload only when the meaning is obvious and matches the built-in behaviour.
Free functions are used for symmetric operators (a + b) and for << on streams. Make comparison operators const and return bool. Do not overload operators for surprising behaviour.
Guided lesson
Work through these steps
- 1.
Read the operator overloading example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
struct Vec2 {
// A small 2D vector.
double x{0.0}, y{0.0};
// Its two components.
};
// End of the struct.
Vec2 operator+(const Vec2& a, const Vec2& b) {
// Defines what a + b means for two Vec2 values.
return Vec2{a.x + b.x, a.y + b.y};
// Add component by component and return the result.
}
// End of operator+.
bool operator==(const Vec2& a, const Vec2& b) {
// Defines equality.
return a.x == b.x && a.y == b.y;
// Equal only when both components match exactly.
}
// End of operator==.
std::ostream& operator<<(std::ostream& out, const Vec2& v) {
// Lets std::cout print a Vec2.
return out << '(' << v.x << ", " << v.y << ')';
// Write the text and return the stream so calls can chain.
}
// End of operator<<.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Operator overloading. Expected result: (4, 6)
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <iostream>
struct Vec2 {
double x{0.0}, y{0.0};
};
// TODO: overload operator+ (add components) and operator<< (print as "(x, y)")
int main() {
Vec2 a{1, 2}, b{3, 4};
std::cout << a + b << '\n';
return 0;
}Expected output
(4, 6)Stuck? Show the full solution (try it yourself first)
#include <iostream>
struct Vec2 {
double x{0.0}, y{0.0};
};
Vec2 operator+(const Vec2& a, const Vec2& b) { return Vec2{a.x + b.x, a.y + b.y}; }
std::ostream& operator<<(std::ostream& out, const Vec2& v) {
return out << '(' << v.x << ", " << v.y << ')';
}
int main() {
Vec2 a{1, 2}, b{3, 4};
std::cout << a + b << '\n';
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Add operator-, operator* by a double, and operator!= to Vec2. Print the sum of two vectors with std::cout, and write tests for each operator.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.