CSIT Object Oriented Programming with C++(Binary plus Operator Overloading ) Part V

I am assuming that, You have already studied Part I,II,III & IV  of Operator Overloading Series. So in this post, I am going to teach you How to perform Binary operator overloading.

Here, I will overload '+' operator to add two complex numbers. 

So, let's get started,


Lets have a look at code and understand concept.

 //Overloading plus operator to add two complex numbers.

#include <iostream>

using namespace std;

class complex

{

    int real,imaginary;

    public:

        void getdata(int a, int b){

                real=a;

                imaginary=b;

        }

        void display(){

            cout<<real<<" + "<<imaginary<<"i"<<endl;

        }

        complex operator +(complex c1)

        {

            complex c;

            c.real=real+c1.real;

            c.imaginary=imaginary+c1.imaginary;

            return c;

        }

};

int main()

{

    complex p1,p2,p;

    p1.getdata(45,60);

    p2.getdata(30,15);

    p=p1+p2;

    p.display();

    return 0;

}


OUTPUT :

 75+75i


If we use friend function, we have to do following changes in writing operator function.

First declare operator function as friend of class complex, like

friend complex operator +(complex c1,complex c2);

Then define it outside class as follows.

complex operator +(complex c1,complex c2)

        {

            complex c;

            c.real=c1.real+c2.real;

            c.imaginary=c1.imaginary+c2.imaginary;

            return c;

        }

In next post, I will teach you overloading Insertion (<<) and Extraction (>>) operator. So refer next  post for that topic.


If This post Helped you, Please leave a comment, and share with your Coder Friends.
Thank You.

Keep Learning, Keep Growing

Comments

Popular posts from this blog

CSIT Object Oriented Programming with C++(Insertion and Extraction Operator Overloading ) Part VI

CSIT Object Oriented Programming with C++(Unary Operator Overloading using Friend function) Part IV

CSIT Object Oriented Programming with C++(Unary Operator Overloading) Part III