Function overloading is a feature of object oriented programming where two or more functions can have the same name but different parameters.
When a function name is overloaded with different jobs it is called Function Overloading.
In Function Overloading “Function” name should be the same and the arguments should be different.
Function overloading can be considered as an example of polymorphism feature in C++.
Following is a simple C++ example to demonstrate function overloading.
#include <iostream>
using namespace std;
void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
Output:
Here is int 10
Here is float 10.1
Here is char* ten
How Function Overloading works?
Exact match:- (Function name and Parameter)
If a not exact match is found:–
>Char, Unsigned char, and short are promoted to an int.
>Float is promoted to double
If no match found: ->C++ tries to find a match through the standard conversion.
ELSE ERROR
Function overloading and return type
Functions that cannot be overloaded in C++
Function overloading and const keyword
Function Overloading vs Function Overriding in C++
Advantages of Function Overloading in C++
1.The main advantage of FUnction overloading is that it improves code and allows code reusability
2.The use of function overloading is to save memory space,consistency,readability.
3.It speeds up the execution of the program
4.Code maintainance also becomes easy.
5.Function overloading brings flexibility to code.
Disadvantages of function overloading
1.Function declarations that differ only in the return type cannot be overloaded.
Illustration:
int fun();
float fun();
It gives an error because the function cannot be overloaded by return type only
2.Member function declaration with the same name and the same parameter types cannot be overloaded if any of them is a static member function declaration.
3.The main disadvantage is that it requires requires the compiler to perform name mangli g on the function name to include information about the arguement types.