Pages

Sunday, May 11, 2025

Operator Overloading in OOPs

 #include <iostream>

using namespace std;

// class Print {
// public:
//     void show(int x) {
//         cout << "int: " << x << endl;
//     }    

//     void show(string str) {
//         cout << "string: " << str << endl;
//     }

// };


class Complex {
    int real;
    int img;

public:
    Complex(int r, int i) {
        real = r;
        img = i;
    }

    void showNum() {
        cout << real << " + " << img << "i \n";
    }

    //Operator overloading
    Complex operator + (Complex &c2)
    {
        int resReal = this->real + c2.real;
        int resImg = this->img + c2.img;
        Complex c3(resReal, resImg);
        return c3;
    }
};

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

    c1.showNum(); // mistake:- tried printing using cout
    c2.showNum(); // same mistake tried printing using cout
   

    Complex c3 = c1+c2;
    c3.showNum();
   
    return 0;
}

OUTPUT:
1 + 2i 3 + 4i 4 + 6i

No comments:

Post a Comment

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...