Operator Overloading in C++

Operator overloading means giving capability to the operator to work on different types of operands.The operators +,*, etc work on operands of type int,float,etc.we can overload these operators by giving them the  capability to work on user-defined data types.

For example,to add two structure variables of type data we can write the following code;

struct data
{
      int i;
      float f;
};
data c,a={1,2.5f},b={3,5.5f};
c = a+b;

instead of,
c.i=a.i+b.i;
c.f=a.f+b.f;

in a+b,the '+' operator is overloaded to add two structure variables.we would of course have to provide the overloaded operator + function to carry out the addition.

No comments:

Post a Comment