C++ Operator Overloading: Customizing Syntax for User-Defined Types

Operator Overloading provides a clean, intuitive syntax for user-defined classes by extending the behavior of built-in C++ operators without altering their precedence or arity.

Example: Complex Number Addition & Stream Insertion (<<)

#include <iostream>

class Complex {
private:
    double real;
    double imag;

public:
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}

    // Overloading '+' operator as a member function
    Complex operator+(const Complex& other) const {
        return Complex(real + other.real, imag + other.imag);
    }

    // Overloading '<<' stream operator as a friend function
    friend std::ostream& operator<<(std::ostream& out, const Complex& c) {
        out << c.real << " + " << c.imag << "i";
        return out;
    }
};

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

    Complex c3 = c1 + c2; // Clean, mathematical syntax!
    std::cout << "Result: " << c3 << std::endl; // Output: 5 + 7i
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Which operators CANNOT be overloaded in C++?

The following four operators CANNOT be overloaded: Scope resolution (::), Member access (.), Pointer-to-member (.*), and Ternary conditional (?:).

Q2. Why must the stream insertion operator (<<) be overloaded as a friend or free function?

Because the left-hand operand of 'std::cout << obj' is 'std::cout' (an ostream object), not your class. If implemented as a member function, you would be forced to write 'obj << std::cout', which violates standard C++ idiom.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

C++ Operators

Precedence and associativity of operators.

Friend Functions

Using friend functions for stream overloading.

Move Assignment

Overloading operator= for move semantics.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!