What is operator overloading? Write different rules to overload operators. Also, explain Operator overloading with an example.

SOLUTION....

✨ Operator Overloading in C++

📌 Definition

Operator overloading is a feature in C++ that allows programmers to redefine the way operators work for user-defined types (like classes and structures).
In other words, we can give special meaning to operators (+, -, *, ==, etc.) when they are used with objects.

For example, instead of only adding integers, we can overload the + operator to add two objects of a Complex class.

📌 Rules for Operator Overloading

  1. Only existing operators can be overloaded → You cannot create new operators (like ** or %%).

  2. The meaning of an operator cannot be changed for built-in types → e.g., you cannot redefine 3 + 5.

  3. At least one operand must be a user-defined type (class/struct).

  4. Some operators cannot be overloaded, like:

    • :: (scope resolution)

    • . (member access)

    • .* (member pointer access)

    • sizeof

    • ?: (ternary operator)

  5. Operators can be overloaded as member functions or friend functions.

  6. Unary operators take no arguments when defined as member functions, but take one argument when defined as friend functions.

  7. Binary operators take one argument when defined as member functions (the left operand is the calling object), but two arguments when defined as friend functions.


#include <iostream>
using namespace std;

class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i = 0) {
        real = r;
        imag = i;
    }

    // Operator overloading for +
    Complex operator + (const Complex &obj) {
        Complex temp;
        temp.real = real + obj.real;
        temp.imag = imag + obj.imag;
        return temp;
    }

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

int main() {
    Complex c1(3, 4), c2(2, 5), c3;

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

    cout << "First Complex Number: ";
    c1.display();
    cout << "Second Complex Number: ";
    c2.display();
    cout << "Sum: ";
    c3.display();

    return 0;
}

OUTPUT

📌 Explanation

  • c1 + c2 calls the overloaded function operator+().

  • Inside the function, the real parts and imaginary parts are added separately.

  • A new object c3 is returned with the result.

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.