What happens when you overload a function?

Function overloading is a C++ programming feature that allows us to have more than one function having same name but different parameter list, when I say parameter list, it means the data type and sequence of the parameters, for example the parameters list of a function myfuncn[int a, float b] is [int, float] which is different from the function myfuncn[float a, int b] parameter list [float, int]. Function overloading is a compile-time polymorphism.
Now that we know what is parameter list lets see the rules of overloading: we can have following functions in the same scope.

sum[int num1, int num2]
sum[int num1, int num2, int num3]
sum[int num1, double num2]

The easiest way to remember this rule is that the parameters should qualify any one or more of the following conditions, they should have different type, number or sequence of parameters.

For example:
These two functions have different parameter type:

sum[int num1, int num2]
sum[double num1, double num2]

These two have different number of parameters:

sum[int num1, int num2]
sum[int num1, int num2, int num3]

These two have different sequence of parameters:

sum[int num1, double num2]
sum[double num1, int num2]

All of the above three cases are valid case of overloading. We can have any number of functions, just remember that the parameter list should be different. For example:

int sum[int, int]
double sum[int, int]

This is not allowed as the parameter list is same. Even though they have different return types, its not valid.

Function overloading Example

Lets take an example to understand function overloading in C++.

#include 
using namespace std;
class Addition {
public:
    int sum[int num1,int num2] {
        return num1+num2;
    }
    int sum[int num1,int num2, int num3] {
       return num1+num2+num3;
    }
};
int main[void] {
    Addition obj;
    cout

Chủ Đề