In C++ there are two types of overloading; function overloading and operator overloading.
More than one function with same name but different number of parameters in a program is called function overloading. If we declare two functions with a same name, the compiler will generate an error, therefore, the compiler distinguish between these functions by their parameters. The common use of function overloading is to provide multiple constructors in a class.
The operator overloading is very different from function overloading. To overload an operator means to do operations on the objects e.g. to add the objects etc. Objects are user defined and operators like +, -, *, etc. are primitive operators. Therefore, it is not possible without operator overloading. Consider the following example. In this example, we have overloaded (+) operator:
point(int a, int b);
point operator +(point p);
x=0; y=0; }
point :: point (int a, int b)
x=a; y = b; }
void point ::print()
point point :: point operator + (point p)
temp.x = x+p.x;
temp.y = y +p.y;
point p1(2,3), p2(4,5), p3;
p3= p1 + p2;
Working of above program:
The constructor point() is called when the object p3 is created. p1 and p2 calls the same constructor and hence x and y have two values. In the main() function the line p3=p1+p2 has a special meaning. It calls the function point operator +(point p). The control is transferred to the definition of this function. Here p1 is automatically called that is its values are automatically passed to function and the values of p2 are stored in p
The result of this addition is stored in p3 object and this object is used to call the print function hence the values of x and y will be 6 and 8 respectively. This type of operator overloading is called binary operator overloading as (+) is a binary operator. Likewise (*) operator or any other operator can also be overloaded using the same method.
Unary operator overloading
time(int h, int m);
time::time(int h, int m)
cout<<“hours : minutes = “<<hours<<” : “<<minutes<<endl;
Working of the above program:
The above program is overloading pre increment and post increment operators. For post increment we have to write int in the brackets as a parameter. In the main() function ++t6 calls the function of pre increment operator then the hours and minutes are incremented and printed. When the control is transferred to the function the object passes the values of hours and minutes and returns them, then print function is called with the incremented object that t6 and here the values of hours and minutes are printed. Similarly t7++ calls the post increment operator function and so on.