Function Overloading
Two or more functions having the same name but different argument(s) are known as overloaded functions.
In C++ programming, two functions can have the same name if the number and/or type of arguments passed is different.
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Here, all 4 functions are overloaded functions because argument(s) passed to these functions are different.
Two or more functions having the same name but different argument(s) are known as overloaded functions.
In C++ programming, two functions can have the same name if the number and/or type of arguments passed is different.
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Here, all 4 functions are overloaded functions because argument(s) passed to these functions are different.
Example : Function Overloading
#include <iostream>
using namespace std;
void display(int);
void display(float);
void display(int, float);
int main() {
int a = 5;
float b = 5.5;
display(a);
display(b);
display(a, b);
return 0;
}
void display(int var) {
cout << "Integer number: " << var << endl;
}
void display(float var) {
cout << "Float number: " << var << endl;
}
void display(int var1, float var2) {
cout << "Integer number: " << var1;
cout << " and float number:" << var2;
}
Output
Integer number: 5 Float number: 5.5 Integer number: 5 and float number: 5.5
Here, the
display() the function is called three times with different type or a number of arguments.
Function overloading is usually used to enhance the readability of the program. If you have to perform one single operation but with different number or types of arguments, then you can simply overload the function
Different ways to Overload a Function
- By changing number of Arguments.
- By having different types of argument.
Comments
Post a Comment