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.
::, .?, sizeof, ?:, etc.) cannot be overloaded.<aside> 💡
Read more: https://www.geeksforgeeks.org/operator-overloading-cpp/
</aside>
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: