DEV Community

Cover image for Operator Overloading Example1
venkateshatgit
venkateshatgit

Posted on

Operator Overloading Example1

Easy way to understand oops is to code it, run it, debug it. Repeat it till you get something new every iteration.

The below program is self explanatory and easy to understand.

Leave comment if you find hard to understand and I will be there to help (Let me know what error you get)

Follow step by step, first code for '+' operator and see the results and next other operator one by one.

Complex Class

#include <bits/stdc++.h>
using namespace std;

class Complex{
        int a, b;
    public:
        Complex(){
            //default constructor
        }

        Complex(int x, int y){
            a=x;
            b=y;
        }

        void display();
        //Binary operator
        Complex operator+(Complex);
        Complex operator-(Complex);
        Complex operator*(Complex);

        //unary operator
        void operator++();
        void operator--();
        Complex operator++(int);

};

void Complex::display(){
    cout<<a<<" + i"<<b<<endl;
}



int main(){

    Complex c1(3, 4), c2(5, 6), c3, c4, c5, c6, c7;
    c1.display();
    c2.display();

    c3 = c1 + c2;
    c3.display();

    c4 = c2 - c1;
    c4.display();

    c5 = c1 * c2;
    c5.display();

    ++c1;
    c1.display();

    --c2;
    c2.display();

    c6 = c5;
    c6.display();
    ++c5;
    c6.display();
    c5.display();

    c7=c4++;
    c4.display();
    c7.display();

    return 0;
}

Complex Complex::operator+(Complex c2){

    Complex c;
    c.a = this->a + c2.a;
    c.b = this->b + c2.b;

    return c;
}

Complex Complex::operator-(Complex c2){

    Complex c;
    c.a = this->a - c2.a;
    c.b = this->b - c2.b;

    return c;
} 

Complex Complex::operator*(Complex c2){

    Complex c;
    c.a = this->a * c2.a - this->b * c2.b;
    c.b = this->a * c2.b + this->b * c2.a;

    return c;
}

void Complex::operator++(){

    this->a = this->a + 1;
    this->b = this->b + 1;
}

void Complex::operator--(){

    this->a = this->a - 1;
    this->b = this->b - 1;
}

Complex Complex::operator++(int){
    Complex c;
    c.a = this->a;
    c.b = this->b;

    this->a = this->a + 1;
    this->b = this->b + 1;

    return c;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
serkzex profile image
Mujtaba Aldebes

Since you are overloading some operators you could overload the operator << and delete the display function.

Collapse
 
venkateshatgit profile image
venkateshatgit

will do that