๐ 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 twoComplex
objects.- When
c1 + c2
is executed, it callsc1.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:
Concept | Explanation |
---|---|
Operator Overloading | Redefining the functionality of operators |
Purpose | To use operators with user-defined types |
Example Used | + for adding Complex numbers |
Benefit | More natural and readable code |