Function overloading lets you create multiple functions with the same name but different inputs. This helps keep your code simple and easy to read.
0
0
Function overloading in C++
Introduction
When you want to perform similar actions but with different types of data.
When you want to use the same function name for different numbers of inputs.
When you want to make your code easier to remember and use.
When you want to avoid creating many different function names for similar tasks.
Syntax
C++
return_type function_name(parameter_list1) {
// code
}
return_type function_name(parameter_list2) {
// code
}Each function must have a different parameter list (different types or number of parameters).
The return type alone cannot distinguish overloaded functions.
Examples
Two functions named
add: one adds integers, the other adds doubles.C++
int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; }
Two
print functions: one for integers, one for strings.C++
void print(int a) { std::cout << "Integer: " << a << std::endl; } void print(std::string s) { std::cout << "String: " << s << std::endl; }
Sample Program
This program shows two multiply functions: one for integers and one for doubles. The right one is called based on the input types.
C++
#include <iostream> #include <string> int multiply(int a, int b) { return a * b; } double multiply(double a, double b) { return a * b; } int main() { std::cout << multiply(3, 4) << std::endl; // calls int version std::cout << multiply(2.5, 4.0) << std::endl; // calls double version return 0; }
OutputSuccess
Important Notes
Function overloading works by matching the function call with the best parameter list.
If no matching function is found, the compiler will give an error.
Overloading helps keep function names simple and meaningful.
Summary
Function overloading allows multiple functions with the same name but different parameters.
It makes code easier to read and use by handling different input types or counts.
The compiler chooses the correct function based on the arguments you provide.