What is operator overloading in C++?

Operators in C++ allow us to perform operations like addition, subtraction, or comparison. However, what if you want to define how these operations work for your own data types, like adding two custom Point objects or comparing two Student objects? This is where operator overloading comes in.

What are operators?

Operators are special symbols or keywords in C++ that perform operations on variables and values. Common operators include:

  • Arithmetic operators (+, -, *, /)

  • Comparison operators (==, !=, <, >)

  • Logical operators (&&, ||, !)

Operator overloading is a feature in C++ that allows us to redefine the way an operator works for user-defined types. For example, the + operator can be overloaded to add two objects instead of just numeric values.

Now that we know what operator overloading is, let's explore how to overload some common operators with examples.

Types of operator overloading

Operator overloading can be classified into the following types:

  1. Unary operators: Overload operators like -, ++, and -- that work with a single operand.

  2. Binary operators: Overload operators like +, -, *, ==, and / that works with two operands.

  3. Relational operators: Overload operators like ==, <, and > to compare objects.

  4. Stream operators: Overload << and >> for input and output streams.

  5. Assignment operators: Overload = to customize assignment behavior.

Note: We can overload almost all operators in C++ to customize their behavior for your classes, except a few like sizeof or ::.

Example of operator overloading in C++

Consider a simple example of a Point class:

#include <iostream>
using namespace std;
class Point {
int x, y;
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
// Overloading the '+' operator
Point operator+(const Point& p) {
return Point(x + p.x, y + p.y);
}
// Overloading the '-' operator
Point operator-(const Point& p) {
// Write your code here
}
void display() const {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1(3, 4), p2(1, 2);
// Adding two points using overloaded '+'
Point p3 = p1 + p2;
cout << "Addition of Points: ";
p3.display(); // Output: (4, 6)
// Subtracting two points using overloaded '-'
Point p4 = p1 - p2;
cout << "Subtraction of Points: ";
p4.display(); // Output: (2, 2)
return 0;
}

Your task is to implement the same functionality for the - operator in line 17 to subtract one Point object from another.

Difference between operator functions and normal functions

Operator Functions

Normal Functions

Used to overload operators for user-defined types.

Perform standard operations or tasks defined by the programmer.

Defined using the operator keyword followed by the operator symbol (e.g., operator+).

Defined with a standard function name chosen by the programmer.

The name is predefined and specific to the operator being overloaded (e.g., operator+, operator-).

The name is user-defined and can be anything valid in C++ (e.g., add, subtract).

Typically returns an object or value based on the operation performed.

Can return any type, including void, depending on the task.

Common pitfalls in operator overloading

  • Incorrect return types: Ensure the correct return type, like returning a reference (*this) in the assignment operator.

  • Missing *this in assignment: Always return *this in the assignment operator to avoid assignment issues.

  • Overloading restrictions: Some operators (e.g., ::, sizeof, .) cannot be overloaded.

  • Edge cases: Handle cases like self-assignment and null pointers to avoid errors.

  • Misleading semantics: Ensure overloaded operators behave as expected (e.g., + should add, not multiply).

Key takeaways

  • Operator overloading allows you to change how operators work with your own classes.

  • It makes your code easier to read by using familiar operators for custom types.

  • Make sure overloaded operators behave as expected to keep the code clear.

Start your programming journey with our Learn C++ Course. This course offers step-by-step guidance, hands-on examples, and practical exercises to help you build a strong foundation in C++. Looking to go from beginner to expert? Explore the Become a C++ Programmer Path. This skill path covers everything from the basics of C++ to advanced programming concepts, with the skills needed to excel in real-world projects.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What are the 5 rules of operator overloading?

  • Rule 1: While you can overload + for your class, its precedence and associativity will remain the same. For instance, a + b * c will evaluate as a + (b * c).
  • Rule 2: You cannot overload assignment operators (like =) for built-in data types.
  • Rule 3: Operator overloading must be done using either member functions or friend functions.
  • Rule 4: At least one operand must be of a user-defined type.
  • Rule 5: Some operators, like the comma operator (,), scope resolution operator (::), sizeof, and typeid, cannot be overloaded.

What is the correct way to overload the operator?

To overload an operator, you define a function as either a member function of the class or a friend function. The function should have the appropriate signature for the operator being overloaded and should operate on user-defined types.


What is the difference between function overloading and operator overloading in C++?

  • Function overloading allows defining multiple functions with the same name but different parameter types or numbers of parameters.
  • Operator overloading allows modifying the behavior of operators (such as +, -, *, etc.) for user-defined types.

Which operators cannot be overloaded in C++?

The following operators cannot be overloaded:

  • Scope resolution operator (::)
  • Sizeof operator
  • Typeid operator
  • Member selector (.)
  • Member pointer selector (.*)
  • Conditional (ternary) operator (?:)

Free Resources