C++ Function Overloading

The C++ function overloading can be defined as if two (or) more function shaving the same name but different arguments are known as “function overloading“. And the overloaded functions must be different in their argument list and with a different data type. The concept of overloading is used when the program blocks conceptually execute the same task but with a slight variation in the set of parameters.



C++ Function Overloading

The main goal of overloading is used to avoid redundant code when the same method name (or) operator is used for multiple times.  The actual method that gets called during runtime is resolved at compile time, thus avoiding runtime errors.

Overloading provides code clarity. And also reduce complexity, and increases runtime presentation of a code. This can be called as an example of polymorphism feature in C++.

Example: function overloading when a number of arguments vary

#include<iostream>    
using namespace std;    
class Cal {    
    public:    
static int add(int a,int b){      
        return a + b;      
    }      
static int add(int a, int b, int c)      
    {      
        return a + b + c;      
    }      
};     
int main(void) {    
    Cal C; //class object declaration.   
    cout<<C.add(10, 20)<<endl;      
    cout<<C.add(12, 20, 23);     
   return 0;    
}

Output:

30
55

Example: function overloading with different types of arguments

#include<iostream>  
using namespace std;  
int mul(int,int);  
float mul(float,int);  
int mul(int a,int b)  
{  
    return a*b;  
}  
float mul(double x, int y)  
{  
    return x*y;  
}  
int main()  
{  
    int r1 = mul(6,8);  
    float r2 = mul(0.2,4);   
    std::cout<<"r1 is : "<<r1<< std::endl;  
    std::cout<<"r2 is : "<<r2<< std::endl;  
    return 0;  
}

Output:

r1 is: 48
r2 is : 0.8