18 Jul C++ Overloading
In C++, we can easily create more than one function with a similar name but different parameters. Let’s say we have the following function:
1 2 3 |
int demoAdd(int a, int b) |
We can create more functions with the same name:
1 2 3 4 |
int demoAdd(int a, int b) double demoAdd(double a, double b) |
Above, we have different types and numbers of parameters for functions with similar names.
The 1st will add two integers and the 2nd two doubles. This is called Function Overloading. For the same action i.e., addition here, by overloading, we do not need to use different function names.
Let us see two examples:
- We will add numbers of different types (int and double) when the number of parameters is the same
- We will add integers when the number of parameters is different:
Add numbers of different types (int and double)
Let us see the 1st example. We will overload the demoAdd() function and add two integers and then two doubles:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> using namespace std; // The demoAdd() function is overloaded // Adding two integer values int demoAdd(int a, int b) { return a + b; } // Adding two double values double demoAdd(double a, double b) { return a + b; } int main() { int n1 = demoAdd(20, 45); double n2 = demoAdd(5.81, 9.44); // Displaying the result cout << "Adding two integers = " << n1 << "\n"; cout << "Adding two doubles = " << n2; return 0; } |
Output
1 2 3 4 |
Adding two integers = 65 Adding two doubles = 15.25 |
Add integers of similar types but different counts of parameters
Let us see another example where we will add integers when the count of parameters is different:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> using namespace std; // The demoAdd() function is overloaded // Adding two integer values int demoAdd(int a, int b) { return a + b; } // Adding three integer values int demoAdd(int a, int b, int c) { return a + b + c; } int main() { int n1 = demoAdd(20, 45); int n2 = demoAdd(30, 60, 72); // Displaying the result cout << "Adding two integers = " << n1 << "\n"; cout << "Adding three integers = " << n2; return 0; } |
Output
1 2 3 4 |
Adding two integers = 65 Adding three integers = 162 |
No Comments