+ 1
What is function overloading????
3 Answers
+ 3
same function name, different parameters.
It can behave different depending on what you send as parammeters.
+ 2
Function overloading lets you modify you function to accept different number or type of arguments after it has been declared.
Take a look at this example :
#include <iostream>
int sum(int a, int b)
{
return a + b;
}
double sum(double a, double b, double z)
{
return a + b;
}
int main()
{
double x = 5;
double y = 6.6;
double z = 11.1;
std::cout << sum(x,y) << std::endl;
std::cout << sum(x,y,z) << std::endl;
}
As you see first we declared function to accept integers and later it has been changed to accept double type and one more argument.
If you execute this code you will get :
11
11.6
This is because in in first call function will use 2 argument version and result will be an integer number. In second call it will use double version(because of 3 provided arguments) and will return double type.
+ 1
Function overloading (also method overloading) is a programming concept that allows programmers to define two or more functions with the same name.
Each function has a unique signature (or header), which is derived from:
function/procedure name
number of arguments
arguments' type
arguments' order
arguments' name
return type
Since functions' names are in this case the same, we must preserve uniqueness of signatures, by changing something from the parameter list (last three alienees).
If the functions' signatures are sufficiently different, the compiler can distinguish which function was intended to be used at each occurrence. This process of searching for the appropriate function is called function resolution and can be quite an intensive one, especially if there are a lot of equally named functions.
Programming languages supporting implicit type conventions usually use promotion of arguments (i.e. type casting of integer to floating-point) when there is no exact function match. The demotion of arguments is rarely used.
When two or more functions match the criteria in function resolution process, an ambiguity error is reported by compiler. Adding more information to compiler by editing the source code (using for example type casting), can address such doubts.
The example code shows how function overloading can be used. As functions do practically the same thing, it makes sense to use function overloading.
function int generateNumber(int MaxValue) {
return rand * MaxValue
}
function int generateNumber(int MinValue, int MaxValue) {
return MinValue + rand * (MaxValue - MinValue)
}
calling the first function[edit]
The first code block will generate numbers from 0 up to specified parameter MaxValue. The appropriate function call is:
int Number := generateNumber(10)
calling the second function[edit]
The second requires another parameter MinValue. Function will return numbers above or equals MinValue and lower than MaxValue.
int Number := generateNumber(6, 10)