What is function overloading?

Function overloading is a feature of c++  which enable us to define multiple functions with the same name provided these functions must differ in their number, order or type of arguments.

#include<iostream>
using namespace std;

         void sum( int a, int b);
         int sum( float a, float b);
         void sum(int a,float b);
int main()
{
         int a=5;
         int b=6;
         float c = 3.2;

         sum(a, b);
         sum(c , c);
         sum(b, c);
return 0;
}

void sum( int a, int b)
{
        a = a + b;
        cout<<a<<endl;
}
int sum (float a, float b)
{
      a= (a + b);
      cout<<a<<endl;
      return static_cast<int>(a);
}
void sum( int a, float b)
{
     float c = a + b;
     cout<<c<<endl;
}

The function overloading does not depend upon return type.why?

Let us try below code.

#include<iostream>
using namespace std;

void sum( int a, int b);
int sum( int a, int b);
int main()
{
return 0;
}

Error will look like:

func.cpp:5:22: error: new declaration ‘int sum(int, int)’
 int sum( int a, int b);
                      ^
func.cpp:4:6: error: ambiguates old declaration ‘void sum(int, int)’
 void sum( int a, int b);

So it is clear that compiler sees the ambiguity in the function sum that is the sum which is returning void or the sum which is returning int. That why function overloading does not depend upon return type of function.

Advantage of function overloading

In the above in example in “what is function overloading section” we have declare

         void sum( int a, int b);
         int sum( float a, float b);
         void sum(int a,float b);

without function overloading we have to give three names of function sum. like

         void sum_1( int a, int b);
         int sum_2( float a, float b);
         void sum_3(int a,float b);

while all these function is doing the same work but without function overloading feature we have to assign different names to these function. here we get advantage of using function overloading , we can create same function name with different types of arguments.



Related Contents to follow