Table of Contents
Function overloading allows multiple functions to have the same name while having different parameter lists. The compiler determines which overloaded function to call based on the number, types, and order of the arguments supplied.
Function overloading allows related operations to use a common function name while supporting different types or combinations of input.
Source Code #
#include <iostream>
int add(int first, int second)
{
return first + second;
}
double add(double first, double second)
{
return first + second;
}
int main()
{
int integer_result = add(10, 20);
double decimal_result = add(10.5, 20.5);
std::cout << "Integer Result: " << integer_result << '\n';
std::cout << "Decimal Result: " << decimal_result << '\n';
return 0;
}
Output #
Integer Result: 30
Decimal Result: 31
Explanation #
- Two functions named
addare defined with different parameter types. int add(int first, int second)accepts twointparameters.double add(double first, double second)accepts twodoubleparameters.- These functions form an overloaded function set.
add(10, 20)selects theintversion because both arguments are integers.add(10.5, 20.5)selects thedoubleversion because both arguments aredoublevalues.- The compiler determines the appropriate overload during compilation based on the function arguments.
- A function cannot be overloaded solely by changing its return type.
return 0;terminates the program successfully.