Function Overloading in C++
Function overloading in C++ allows you to define multiple functions with the same name within the same scope, but with different parameters. The compiler determines which function to call based on the number or types of arguments provided when the function is invoked. Function overloading is a form of polymorphism in C++ and is a useful feature for creating more readable and maintainable code by providing multiple ways to call a function with different argument combinations.
Here’s how you can use function overloading in C++:
#include <iostream>
// Function with no parameters
void print() {
std::cout << "No arguments provided." << std::endl;
}
// Function with one integer parameter
void print(int num) {
std::cout << "Integer argument: " << num << std::endl;
}
// Function with two double parameters
void print(double num1, double num2) {
std::cout << "Double arguments: " << num1 << " and " << num2 << std::endl;
}
int main() {
print(); // Calls the first print() function with no arguments
print(42); // Calls the second print() function with an integer argument
print(3.14, 2.71); // Calls the third print() function with two double arguments
return 0;
}
In this example:
- We have three functions named
print
, each with a different set of parameters. The firstprint
function takes no arguments, the second takes an integer, and the third takes two double values. - In the
main
function, we demonstrate function overloading by calling theprint
function with different argument combinations. - The compiler determines which
print
function to call based on the number and types of arguments provided during the function calls.
When you run this program, it will produce the following output:
No arguments provided.
Integer argument: 42
Double arguments: 3.14 and 2.71
Function overloading is not limited to the number of parameters; it also considers the types of parameters. This allows you to create functions with the same name that perform different operations depending on the input types, making your code more versatile and easier to use.