Function Overloading in C++

Let us look as abs() function in C. You should abs() for int, fabs() for float, labs() for long. All these functions find absolute value of a number. As two functions can not have same name, C library has so many names for abs function. This is not the case in C++

In C++, two or more functions can have the same name if they have different number of parameters or different types of parameters. These are called overloaded functions. 

Overloaded functions must differ by number of parameters or types of parameters or both. In case of class members, they can differ by const-ness.



int sum(int a,int b) {return a+b;}
int sum(int a,int b,int c){ return a+b+c;}
float sum(float m,float n) {return m+n;}

These three are all overloaded functions sum.

Two functions can not be overloaded, if they differ only by their return types.

int product(int a,int b);
float product(int a,int b);/*invalid*/


When an overloaded function is called, the compiler calls a version based on type of arguments and number of arguments.


int x,int y;

x=y=33;
x = sum(x,y,x+4);/*calls 3 parameter sum function*/

float m=sum(8.9f,1.2f);/*calls float sum function*/

double n=sum(12.1,3.2);/*ambiguity error*/



Last line produces compiler error because the compiler does not know whether to convert parameter to float or int.

As you can see, some times, the overloaded functions are very similar except for types of parameters. In such cases, we can use template functions which are generic functions. 

C++ also has another type of overloading for classes. That is operator overloading where operator behavior is modified for the given class. 

Get these notes in your mobile. Download my C++ Notes app.

Comments

Popular Posts