Operator Overloading - Tryhardtocarry/2143-oop GitHub Wiki

Operator Overloading

Definition

Operator overloading allows us to define how built-in operators (+, -, ++, ==, etc.) work for user-defined types (classes).
This makes objects behave like built-in types, improving code readability.


** Example: Overloading the ++ Operator (Increment)**

#include <iostream>
using namespace std;

// Class representing a simple counter
class Counter {
private:
    int value; // Stores the counter value

public:
    // Constructor to initialize the counter
    Counter(int v) : value(v) {}

    // Overloading the ++ operator (prefix version)
    Counter operator++() {
        ++value; // Increment the counter
        return *this; // Return the updated object
    }

    // Function to display the current counter value
    void display() {
        cout << "Counter Value: " << value << endl;
    }
};

int main() {
    // Create a Counter object with an initial value of 5
    Counter count(5);

    cout << "Before increment: ";
    count.display(); // Display initial value

    ++count; // Calls the overloaded ++ operator

    cout << "After increment: ";
    count.display(); // Display updated value

    return 0;
}
 ** Explanation**
- **`operator++()` is overloaded inside the class to modify the value variable.

[C++ Operator Overloading - W3Schools](https://www.w3schools.com/cpp/cpp_operator_overloading.asp)
- [C++ Overloading - cplusplus.com](https://cplusplus.com/doc/tutorial/operators/)
⚠️ **GitHub.com Fallback** ⚠️