Intro to Operator Overload
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 40 of 104.
Operator overloading allows you to define how operators like +, -, or == behave when used with your custom classes. Instead of calling methods like a.add(b), you can write the more intuitive a + b.
In C++, operators are essentially functions with special names. To overload an operator, you define a function using the operator keyword followed by the symbol:
class Vector2D {
double x, y;
public:
Vector2D(double x, double y) : x(x), y(y) {}
// Overload the + operator
Vector2D operator+(const Vector2D& other) const {
return Vector2D(x + other.x, y + other.y);
}
};Now you can add two vectors naturally:
Vector2D v1(1.0, 2.0);
Vector2D v2(3.0, 4.0);
Vector2D v3 = v1 + v2; // Calls v1.operator+(v2)Not all operators can be overloaded. The scope resolution operator ::, member access ., ternary ?:, and sizeof cannot be overloaded. Additionally, you cannot create new operators or change an operator's precedence - * will always be evaluated before +.
Operators can be implemented as member functions (like above) or as non-member functions. In the upcoming lessons, you'll learn when to use each approach and how to overload specific categories of operators.
Challenge
EasyLet's build a Point class that represents a 2D coordinate and supports adding two points together using the + operator. This is your first step into operator overloading — making your custom classes work with familiar operators.
You'll create two files to organize your code:
Point.h: Define aPointclass that stores x and y coordinates (bothint). Your class should have:- Private members for the x and y coordinates
- A constructor that takes x and y values
- Getters
getX()andgetY()(both const) - An overloaded
+operator that adds two points together and returns a newPointwith the combined coordinates
The
+operator should be implemented as a member function that takes anotherPointby const reference and returns a newPoint. Mark it asconstsince it doesn't modify either operand.main.cpp: Read four integers from input (x1, y1, x2, y2 on separate lines) representing two points. Create twoPointobjects, add them together using the+operator, and display the results.Output format:
Point 1: (<x1>, <y1>) Point 2: (<x2>, <y2>) Sum: (<sum_x>, <sum_y>)
The key insight here is that p1 + p2 is actually calling p1.operator+(p2) behind the scenes. Your overloaded operator lets you write intuitive code like Point p3 = p1 + p2; instead of something like Point p3 = p1.add(p2);.
Convert input strings to integers using std::stoi(). Don't forget header guards in your header file.
Cheat sheet
Operator overloading allows you to define how operators like +, -, or == behave with custom classes, enabling intuitive syntax like a + b instead of a.add(b).
To overload an operator, define a function using the operator keyword followed by the symbol:
class Vector2D {
double x, y;
public:
Vector2D(double x, double y) : x(x), y(y) {}
// Overload the + operator
Vector2D operator+(const Vector2D& other) const {
return Vector2D(x + other.x, y + other.y);
}
};Usage:
Vector2D v1(1.0, 2.0);
Vector2D v2(3.0, 4.0);
Vector2D v3 = v1 + v2; // Calls v1.operator+(v2)Some operators cannot be overloaded: ::, ., ?:, and sizeof. You cannot create new operators or change operator precedence.
Operators can be implemented as member functions or non-member functions.
Try it yourself
#include <iostream>
#include <string>
#include "Point.h"
using namespace std;
int main() {
// Read input
string line1, line2, line3, line4;
getline(cin, line1);
getline(cin, line2);
getline(cin, line3);
getline(cin, line4);
int x1 = stoi(line1);
int y1 = stoi(line2);
int x2 = stoi(line3);
int y2 = stoi(line4);
// TODO: Create two Point objects using the input values
// TODO: Add the two points together using the + operator
// TODO: Output the results in the required format:
// Point 1: (<x1>, <y1>)
// Point 2: (<x2>, <y2>)
// Sum: (<sum_x>, <sum_y>)
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container