Function Overloading is a feature of Object Oriented Programming in C++ that allows us to create multiple functions with the same name but different parameters. When the same function name is overloaded with different work in the same scope then it is called function overloading.
Function overloading is based on the concept of polymorphism, which allows a function to take on different forms based on its input or context.
Example:
//example of function overloading int fun(){} int fun(int a, int b){} float fun(double num){}
Overloading Function with Different Parameter Types.
//Overloading Function with different types of parameters. #include<iostream> using namespace std; //function with integer type parameter int sum(int a, int b) { return a + b; } //function with float type parameter float sum(float a, float b) { return a + b; } int main(){ //function call cout << "Sum of two integers: " << sum(5, 10) << endl; cout << "Sum of two floats: " << sum(3.4f, 4.6f) << endl; }
Sum of two integers: 15
Sum of two floats: 8
Overloading Function with Different Number of Parameters.
//Overloading Function with different number of parameters. #include<iostream> using namespace std; //function with three integer parameters int sum(int a, int b, int c) { return a + b + c; } //function with two integer parameters int sum(int a, int b) { return a + b; } //function with two float parameters float sum(float a, float b) { return a + b; } int main(){ //function call cout << "Sum of three integers: " << sum(5, 10, 5) << endl; cout << "Sum of two integers: " << sum(12, 5) << endl; cout << "Sum of two floats: " << sum(3.5f, 4.5f) << endl; }
Sum of three integers: 20
Sum of two integers: 17
Sum of two floats: 8
No comments:
Post a Comment