Operator Overloading in C++

 


1️⃣ What is Operator Overloading?

Operator overloading in C++ allows us to redefine operators (+, -, *, etc.) for user-defined types like classes and structs. It enables objects to behave more like built-in types.

Key Features:

✅ Allows custom behavior for operators when applied to objects.
✅ Achieved using the operator keyword.
✅ Supports most operators except ::, .*, ., and ?:.


2️⃣ Syntax of Operator Overloading

class ClassName {
public:
    ReturnType operator Symbol (Arguments) {
        // Operator overloading logic
    }
};

🔹 operator is a keyword.
🔹 Symbol is the operator being overloaded (e.g., +, -).
🔹 ReturnType is usually an object of the class.


3️⃣ Example: Overloading + Operator

Adding Two Complex Numbers

#include <iostream>
using namespace std;

class Complex {
private:
    double real, imag;

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

    // Overload + operator
    Complex operator+(const Complex& obj) {
        return Complex(real + obj.real, imag + obj.imag);
    }

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

int main() {
    Complex c1(3, 4), c2(2, 5);
    Complex c3 = c1 + c2; // Calls overloaded operator+
    
    cout << "Sum: ";
    c3.display();
    return 0;
}

🔹 Output

Sum: 5 + 9i

4️⃣ Overloading Comparison Operators (==)

Example: Comparing Two Objects

#include <iostream>
using namespace std;

class Distance {
private:
    int meters;

public:
    Distance(int m) : meters(m) {}

    // Overload == operator
    bool operator==(const Distance& obj) {
        return meters == obj.meters;
    }
};

int main() {
    Distance d1(10), d2(10), d3(5);

    cout << "d1 == d2: " << (d1 == d2 ? "True" : "False") << endl;
    cout << "d1 == d3: " << (d1 == d3 ? "True" : "False") << endl;
    
    return 0;
}

🔹 Output

d1 == d2: True
d1 == d3: False

5️⃣ Overloading Increment (++) Operator

#include <iostream>
using namespace std;

class Counter {
private:
    int count;

public:
    Counter() : count(0) {}

    // Overload ++ (Prefix)
    void operator++() {
        count++;
    }

    // Display Count
    void display() {
        cout << "Count: " << count << endl;
    }
};

int main() {
    Counter c;
    ++c; // Calls overloaded ++
    c.display();
    
    return 0;
}

🔹 Output

Count: 1

6️⃣ Overloading << (Insertion) and >> (Extraction) Operators

Example: Input/Output Stream Overloading

#include <iostream>
using namespace std;

class Student {
private:
    string name;
    int age;

public:
    // Overloaded input operator
    friend istream& operator>>(istream& input, Student& s) {
        input >> s.name >> s.age;
        return input;
    }

    // Overloaded output operator
    friend ostream& operator<<(ostream& output, const Student& s) {
        output << "Name: " << s.name << ", Age: " << s.age;
        return output;
    }
};

int main() {
    Student s;
    cout << "Enter name and age: ";
    cin >> s;  // Calls overloaded >> operator
    cout << "Student Details: " << s << endl; // Calls overloaded << operator

    return 0;
}

🔹 Output

Enter name and age: John 21
Student Details: Name: John, Age: 21

7️⃣ Operator Overloading Rules

Only existing operators can be overloaded (No overloading of . or ::).
At least one operand must be a user-defined type (class/struct).
Cannot change the operator’s precedence or associativity.
Use friend function when overloading << and >>.


8️⃣ Summary

Operator Overloading makes user-defined types work like built-in types.
Most operators can be overloaded (+, -, *, ==, [], (), etc.).
Used in classes like Complex, Matrix, Fraction, etc.

Would you like a real-world example like Matrix Addition or Fraction Operations? 🚀

Post a Comment

0 Comments