Skip to content

Defining operator overloading

๐Ÿ“˜ What is Operator Overloading?

Operator Overloading is a feature in C++ that allows you to redefine the meaning of operators (like +, -, *, etc.) for user-defined data types (like classes).

It makes objects of a class behave like built-in types when used with standard operators.


๐Ÿง  Real-Life Analogy:

Just like + means addition for integers and concatenation for strings, we can define what + should do for a class like Complex, Time, or Vector.


๐Ÿ”ง Syntax of Operator Overloading

Operator overloading is done using a special function:

return_type operator op (arguments) {
// body of the function
}

Here:

  • op is the operator to overload (like +, -, ==, etc.)
  • operator is a keyword
  • Can be a member function or a friend function

๐Ÿ“Œ Types of Operators That Can Be Overloaded:

  • Arithmetic: +, -, *, /
  • Comparison: ==, !=, <, >
  • Assignment: =
  • Unary: ++, --
  • Others: [], (), ->

โŒ Some operators cannot be overloaded: ::, ., .*, sizeof, ?:


๐Ÿงช C++ Program: Overloading + Operator for Complex Numbers

#include <iostream>
using namespace std;

class Complex {
private:
float real;
float imag;

public:
Complex() : real(0), imag(0) {}

Complex(float r, float i) {
real = r;
imag = i;
}

// Overload + operator
Complex operator + (Complex c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}

void display() {
cout << real << " + " << imag << "i" << endl;
}
};

int main() {
Complex c1(3.5, 2.5);
Complex c2(1.5, 4.5);

Complex c3 = c1 + c2; // Uses overloaded + operator

cout << "Sum of Complex Numbers: ";
c3.display();

return 0;
}

โœ… Output:

Sum of Complex Numbers: 5 + 7i

๐ŸŽฏ Key Points:

  • operator+ is a member function that defines how to add two Complex objects.
  • When c1 + c2 is executed, it calls c1.operator+(c2) behind the scenes.
  • Makes code more intuitive and object-oriented.

โœ… Advantages:

  • Makes code easier to read and more natural.
  • Enhances usability of custom classes.
  • Allows mathematical operations on objects.

โŒ Limitations:

  • Can be misused to make code confusing.
  • Must be used carefully to maintain meaning and readability.

๐Ÿ“Œ Summary:

ConceptExplanation
Operator OverloadingRedefining the functionality of operators
PurposeTo use operators with user-defined types
Example Used+ for adding Complex numbers
BenefitMore natural and readable code