3.2) Function overloading in C++
Function overloading in C++ allows you to define multiple functions with the same name but different parameter lists. The compiler determines which function to call based on the number and types of arguments provided.
Function overloading provides a way to create more intuitive and flexible APIs while using the same function name for related operations.
Here’s a detailed explanation of function overloading with code examples:
Table of Contents
1. Function Overloading Based on Number of Parameters
You can overload a function by providing different numbers of parameters.
#include <iostream>
// Function overloading based on the number of parameters
int add(int a, int b);
int add(int a, int b, int c);
int main() {
int result1 = add(5, 3);
int result2 = add(5, 3, 2);
std::cout << "Result 1: " << result1 << std::endl;
std::cout << "Result 2: " << result2 << std::endl;
return 0;
}
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
Output:
Result 1: 8
Result 2: 10
2. Function Overloading Based on Parameter Types
You can also overload a function based on the types of parameters.
#include <iostream>
// Function overloading based on parameter types
int sum(int a, int b);
double sum(double a, double b);
int main() {
int result1 = sum(5, 3);
double result2 = sum(2.5, 3.7);
std::cout << "Result 1: " << result1 << std::endl;
std::cout << "Result 2: " << result2 << std::endl;
return 0;
}
int sum(int a, int b) {
return a + b;
}
double sum(double a, double b) {
return a + b;
}
Output:
Result 1: 8
Result 2: 6.2
3. Function Overloading with Different Parameter Orders
Function overloading can also be used to provide different parameter orders.
#include <iostream>
// Function overloading with different parameter orders
void print(int a, double b);
void print(double b, int a);
int main() {
print(5, 3.14);
print(2.71, 10);
return 0;
}
void print(int a, double b) {
std::cout << "int: " << a << ", double: " << b << std::endl;
}
void print(double b, int a) {
std::cout << "double: " << b << ", int: " << a << std::endl;
}
Output:
int: 5, double: 3.14
double: 2.71, int: 10
4. Function Overloading with Default Arguments
Function overloading can also be combined with default arguments for increased flexibility.
#include <iostream>
// Function overloading with default arguments
void printMessage(std::string message = "Hello, World!");
int main() {
printMessage();
printMessage("Custom Message");
return 0;
}
void printMessage(std::string message) {
std::cout << message << std::endl;
}
Output:
Hello, World!
Custom Message
Function overloading provides a way to make your code more expressive and intuitive by using the same function name for related operations. The compiler chooses the appropriate function to call based on the provided arguments, making your code more readable and easier to maintain.