The C++ programming feature of function overloading allows us to have many functions with the same name but different argument lists. When I say parameter list, I’m referring to the data type and order in which the parameters are presented.
The parameter list of a function myfunction(int a, double b), for example, is (int, double), which is different from the parameter list of a function myfunction(double a, int b) (double, int). Overloading is a polymorphism that happens throughout the compilation process. Let’s look at the overloading rules now that we know what a parameter list is:
we can have the following functions in the same scope.
sum(int a, int b)
sum(int a, int b, int c)
Rules –
Three different circumstances or various parameters:
1. The parameter types for these functions are different.
sum(int a, int b)
sum(double a, double b)
2. The number of parameters in these functions varies.
sum(int a, int b)
sum(int a, int b, int c)
3. The parameters of these functions are in a different order.
sum(int a, double b)
sum(double a, int b)
program
#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<<obj.sum(16, 19)<<endl;
cout<<obj.sum(18, 10, 100);
return 0;
}
Output
35
128
Advantages
- It saves memory, maintains consistency, creates a clear interface for methods independent of the parameter type, and improves program readability.
- We can create multiple functions with the same name using the function overloading concept, but the parameters given should be of distinct kinds.
- Overloading functions speed up the program’s execution.
- Function overloading is a technique for reusing code and saving memory.
Disadvantages
- The function overloading procedure cannot be used to overload function declarations that differ by return type.
- The same arguments or name types cannot be overloaded if any static member function is declared.
Interested in learning about similar topics? Here are a few hand-picked blogs for you!
- What is recursion?
- Describe compiler?
- What is programming?
- Explain constructor?
- What is object oriented programming?