🧾 Unit 6: Operator Overloading [6 Hrs]


✍️ What is Operator Overloading?

Operator overloading is a feature in C++ that allows us to redefine the way operators work for user-defined data types (like classes). This helps make code intuitive and natural when using objects.

The main idea behind “Operator overloading” is to use C++ operators with class variables or class objects. Redefining the meaning of operators really does not change their original meaning; instead, they have been given additional meaning along with their existing ones.


🔹 1. Rules and Restrictions for Operator Overloading

<aside> 💡

Read more: https://www.geeksforgeeks.org/operator-overloading-cpp/

</aside>


🔹 2. Overloading Unary Operators

Unary operators like -, ++, --, etc., can be overloaded using member functions or friend functions.

Example: Overload unary minus (-) to reverse the sign of a number

#include <iostream>
using namespace std;

class Number {
private:
    int value;

public:
    Number(int v) {
        value = v;
    }

    void operator-() { // unary minus
        value = -value;
    }

    void display() {
        cout << "Value: " << value << endl;
    }
};

int main() {
    Number num(10);
    -num; // Overloaded unary -
    num.display(); // Output should be -10
    return 0;
}

📝 Output: