Function
overloading in C++ allows you to define multiple functions with the same name but with different parameter lists. The compiler distinguishes between these functions based on the number, types, or order of the parameters. This feature provides flexibility and readability to your code, enabling you to use the same function name for related operations.
#include
<iostream>
int
add
(
int
a,
int
b) {
return
a + b;
}
double
add
(
double
a,
double
b) {
return
a + b;
}
int
add
(
int
a,
int
b,
int
c) {
return
a + b + c;
}
int
main
() {
int
sum1 =
add
(3, 4);
double
sum2 =
add
(2.5, 3.5);
int
sum3 =
add
(1, 2, 3);
std::cout
<<
"Sum 1: "
<< sum1 <<
"
"
;
std::cout
<<
"Sum 2: "
<< sum2 <<
"
"
;
std::cout
<<
"Sum 3: "
<< sum3 <<
"
"
;
return
0;
}
In this example, the add function is
overloaded
three times:
With different parameter types:
One version takes two integers, and another takes two doubles.
With a different number of parameters:
One version takes three integers.
1. Same Function Name:
(a.) Functions must have the same name.
(b.) Overloading is based on the function name.
int
add
(
int
a,
int
b);
double
add
(
double
a,
double
b);
int
add
(
int
a,
int
b,
int
c);
2. Different Parameter Lists:
(a.) Overloaded functions should have different parameter types, a different number of parameters, or both.
int
add
(
int
a,
int
b);
double
add
(
double
a,
double
b);
int
add
(
int
a,
int
b,
int
c);
Benefits of Function Overloading:
a. Readability:
Use the same function name for logically related operations, making the code more readable.
b. Consistency:
Provide a consistent interface for users of your code.
c. Default Arguments Alternative:
Overloading is an alternative to using default arguments for flexibility.
Function
overloading
is a powerful feature in C++ that enhances code
organization
and clarity by allowing you to use
familiar
names for related operations.