Operator Overloading

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.

Key Characteristics

  1. Syntax: Defined using the operator keyword followed by the operator symbol.
  2. Flexibility: Enables intuitive operations on objects.
  3. Consistency: Maintains consistent behavior with built-in types.

Commonly Overloaded Operators

  • Arithmetic (+, -, *, /)
  • Comparison (==, !=, <, >)
  • Assignment (=, +=, -=)
  • Increment/Decrement (++, --)

Example

#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;
}