Function overloading is a feature in C++ that allows you to define multiple functions with the same name, but with different parameters. This means that you can have multiple functions with the same name, but they must have different parameter lists, and the compiler will select the appropriate function based on the arguments passed at the time of function call.
Overloading allows you to reuse the same function name for different purposes, which can make your code more readable and easier to understand. For example, you can have a function named sum()
that can add two integers or two floating-point numbers, and the compiler will automatically select the appropriate function based on the data types of the arguments.
Here's an example to illustrate function overloading:
c++#include <iostream>
using namespace std;
// Function overloading
int sum(int a, int b) {
return a + b;
}
float sum(float a, float b) {
return a + b;
}
int main() {
int x = 5, y = 10;
float a = 1.5, b = 2.5;
cout << "sum(x, y) = " << sum(x, y) << endl; // Output: sum(x, y) = 15
cout << "sum(a, b) = " << sum(a, b) << endl; // Output: sum(a, b) = 4
return 0;
}
In this example, we have defined two functions with the same name sum()
, but with different parameter types (int and float). When we call sum(x, y)
, the compiler automatically selects the int sum(int a, int b)
function, and when we call sum(a, b)
, the compiler automatically selects the float sum(float a, float b)
function.
In summary, function overloading is a powerful feature in C++ that allows you to define multiple functions with the same name, but with different parameter lists, and the compiler automatically selects the appropriate function based on the arguments passed at the time of function call.
Comments
Post a Comment