Operator Overloading is a feature in C++ that allows you to redefine the behavior of operators (like +, -, *, ==, etc.) for user-defined types (e.g., classes). With operator overloading, you can give these operators new meanings when applied to objects of a class. It enables you to use operators intuitively with objects, making code more readable and expressive.
To overload an operator, you define a special function (called an operator function) in the class. The syntax for overloading an operator is:
returnType operator op (parameter_list);
Where:
op is the operator being overloaded (e.g., +, -, =, etc.).class ClassName {
public:
returnType operator symbol (parameter_list);
};
+ OperatorLet's start with overloading the + operator to add two objects of a class. For example, let's consider a Point class that holds x and y coordinates.
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
// Constructor to initialize the coordinates
Point(int x = 0, int y = 0) : x(x), y(y) {}
// Overload the '+' operator to add two Point objects
Point operator + (const Point& p) {
return Point(x + p.x, y + p.y); // Return a new Point object
}
// Function to display the coordinates
void display() const {
cout << "Point(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1(2, 3), p2(4, 5);
Point p3 = p1 + p2; // Calls the overloaded '+' operator
p3.display(); // Output: Point(6, 8)
return 0;
}
operator+ function is overloaded to add two Point objects.Point object, whose x and y values are the sum of the corresponding values from the two objects being added.+ operator can now be used intuitively to add two Point objects.= (Assignment) OperatorThe assignment operator = can be overloaded to allow copying of objects. This is useful when dealing with dynamic memory or deep copying.
#include <iostream>
using namespace std;
class Box {
private:
int length;
public:
// Constructor to initialize length
Box(int len) : length(len) {}
// Overload the assignment operator
Box& operator = (const Box& b) {
// Check for self-assignment
if (this != &b) {
length = b.length;
}
return *this; // Return the current object
}
// Function to display the box's length
void display() const {
cout << "Length: " << length << endl;
}
};
int main() {
Box box1(10);
Box box2(20);
box2 = box1; // Calls the overloaded '=' operator
box2.display(); // Output: Length: 10
return 0;
}
operator= function is overloaded to copy the contents of one Box object into another.this pointer is used to check for self-assignment (i.e., when an object is assigned to itself).*this) to allow chained assignments like box3 = box2 = box1;.== OperatorYou can overload the == operator to compare objects of a class for equality. Here's an example:
#include <iostream>
using namespace std;
class Person {
private:
string name;
int age;
public:
// Constructor to initialize name and age
Person(string name, int age) : name(name), age(age) {}
// Overload the '==' operator to compare two Person objects
bool operator == (const Person& p) {
return (name == p.name && age == p.age);
}
// Function to display person's details
void display() const {
cout << name << " (" << age << " years)" << endl;
}
};
int main() {
Person person1("John", 30);
Person person2("Alice", 25);
Person person3("John", 30);
if (person1 == person3) { // Calls the overloaded '==' operator
cout << "person1 and person3 are equal." << endl;
} else {
cout << "person1 and person3 are not equal." << endl;
}
return 0;
}
operator== function is overloaded to compare two Person objects for equality based on their name and age.== operator for the name and age member variables.true or false).Unary Operators: Operators that work with a single operand (e.g., ++, --, -, !, etc.)
class Counter {
private:
int count;
public:
Counter() : count(0) {}
// Overloading the pre-increment operator
Counter& operator ++ () {
++count;
return *this;
}
void display() const {
cout << "Count: " << count << endl;
}
};
Binary Operators: Operators that work with two operands (e.g., +, -, *, ==, etc.)
// Already shown in the previous examples for operators like '+' and '=='
Stream Operators (<<, >>): These are overloaded to handle input/output operations with objects.
class Box {
private:
int length;
public:
Box(int len) : length(len) {}
// Overloading the stream insertion operator (<<)
friend ostream& operator << (ostream& out, const Box& b) {
out << "Length: " << b.length;
return out;
}
};
int main() {
Box box(10);
cout << box << endl; // Calls the overloaded << operator
return 0;
}
Type Conversion Operators: You can overload operators to convert objects of one type to another.
class Distance {
private:
int feet;
public:
Distance(int f) : feet(f) {}
// Conversion operator to convert Distance to int
operator int() {
return feet;
}
};
int main() {
Distance d(5);
int x = d; // Implicit conversion to int
cout << "Distance in feet: " << x << endl; // Output: Distance in feet: 5
return 0;
}
+ operator to perform subtraction might confuse users of your class.<<) and extraction (>>) operators.Open this section to load past papers