Operator overloading allows custom implementation of operators for user-defined types (classes). This enables operators to be used intuitively with objects, similar to primitive types.
operator
keyword followed by the operator symbol.+
, -
, *
, /
)==
, !=
, <
, >
)=
, +=
, -=
)++
, --
)#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
// Overload + operator
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(1.0, 2.0);
Complex c2(3.0, 4.0);
Complex c3 = c1 + c2;
c3.display(); // Output: 4.0 + 6.0i
return 0;
}