Operator Overloading in C++

  •  Operator overloading is a compile time polymorphism in which the operator is overloaded to provide the special meaning to the user defined data type.
  • Operator overloading is used to predefine most of the operators available in C plus plus.
  • Advantages of operator overloading is to perform different operations on the same operand.
Example program:

// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;


class Complex{
    int a,b;
    public:
    void setData(int x,int y){
        a = x;
        b = y;
    }
    void display(){
        cout<<a<<" + i"<<b<<endl;
    }
    Complex operator +(Complex c1){
        Complex sum;
        sum.a = a + c1.a;
        sum.b = b + c1.b;
        return sum;
    }
};



int main() {
    Complex c1,c2,c3;
    c1.setData(1,2);
    c2.setData(3,4);
    c3 = c1 + c2;
    c3.display();
    return 0;
}


Post a Comment

Previous Post Next Post