Operator overloading

Operator overloading is compile time polymorphism.

The operator overloading provides mechanism to perform operations on user defined data type.

We can give special meaning to any operators in which program it is implemented.

Rules for operator overloading

1.Only existing operator can be overloaded.

2.The overloaded operator must have at least one operand that is user defined type.

3.We cannot change the basic meaning and syntax of an operator.

4.We cannot use friend function to overload certain operators. However member function can be used to overload them.

5.Unary operators, overloaded by means of a member function, take no explicit argument s and return no explicit value, but, those overloaded by means of a friend function, take one reference argument.

6.Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments.

7. When using binary operators overloaded through a member function, the left hand operand must be an object of the relevant class.

8.We cannot overload following operators.

Operator Name

. and.*

Class member access operator
:: Scope Resolution Operator
sizeof() Size Operator
?: Conditional Operator

Example:

#include<iostream.h>
#include<conio.h>
class Complex
{
    int x,y;
    public:
        void getdata()
        {
            cout<<" enter the real nad imaginary parts of a complex number: ";
            cin>>x>>y;
            
        }
        Complex operator +(Complex c)
        {
            Complex c1;
            c1.x=x+c.x;
            c1.y=y+c.y;
            return c1;
        }
        void disp()
        {
            if(y<0)
            {
                cout<<x<<y<<"i";
            }
            else
            {
                cout<<x<<"+i"<<y;
            }
        }
       
};
void main()
{
    clrscr();
    Complex c1,c2,c3;
    c1.getdata();
    c2.getdata();
    c3=c1+c2;
    c3.disp();
    getch();
}