Lesson 21 of 45
C++Lesson 21: Operator Overloading
10 min
Course progress47%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 21 of 45
C++10 min
Keep these ideas in mind as you work through the lesson.
C++ lets you give existing operators new meaning for your own types, making them behave like built‑in types. Overloadable operators include arithmetic, comparison, subscript, function call, and stream insertion/extraction.
Vector2D with arithmetic and stream operatorsclass Vector2D {
double x_, y_;
public:
Vector2D(double x = 0, double y = 0) : x_(x), y_(y) {}
// addition
Vector2D operator+(const Vector2D& rhs) const {
return Vector2D(x_ + rhs.x_, y_ + rhs.y_);
}
// scalar multiplication (member)
Vector2D operator*(double scalar) const {
return Vector2D(x_ * scalar, y_ * scalar);
}
// stream insertion for printing
friend std::ostream& operator<<(std::ostream& os, const Vector2D& v) {
return os << '(' << v.x_ << ", " << v.y_ << ')';
}
};
int main() {
Vector2D a{1, 2}, b{3, 4};
Vector2D c = a + b * 2.0; // uses overloaded * and +
std::cout << \"c = \" << c << '\
';
return 0;
}
Key guidelines:
+, ==).Tip: Overload
operator=and the copy/move constructors together to maintain the rule of three/five.
<Alert type="warning">You cannot overload &&, ||, , (comma), or ?:.