Do you want to learn how to overload a function ? What is Function Overloading ? What does overloaded function means ? How we can use Function Overloading in C++ ? How we can use multiple parameter types in our functions ? Here we go,
Function Overloading is used to operate with the same function by defining it with different variable types. By using Function Overloading, a function can be used with the same name in different parameter types and multiple variations.
In previous posts about functions, we created an addition function add() that has a and b parameters and returns sum of a and b. C++ functions are the most flexible and effective functions for using memory and CPU operations. For example, using integer variables in a function is faster than using long integer variables. Also using correct types may have some benefits to use variables (i.e memory usage, conversion required, etc.). In programming sometimes we may want to use different types of variables and variable variations, here we use Function Overloading.
Let’s remember this integer addition example,
1 2 3 4 5 6 |
int add (int a, int b) { return a+b; } |
We can use this function as in this example below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> int add (int a, int b) { return a+b; } int main() { int x = 300, y = 500; int result = add(x, y); std::cout << result << '\n'; } |
As same this function we can generate a new function to add floating numbers with a name change,
1 2 3 4 5 6 |
float addf (float a, float b) { return a+b; } |
As you see we should use a new name addf() for the operation on the floating point numbers.
If we want to use same function name on both float and integer numbers, we can Overload this function by adding a new declarations and definitions with the same function names as below,
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> int add (int a, int b) // overloaded { return a+b; } float add (float a, float b) // overloaded { return a+b; } int main() { int x = 300, y = 500; int result = add(x, y); std::cout << result << '\n'; float xf = 30.5, yf = 50.5; float resultf = add(xf, yf); std::cout << resultf << '\n'; } |
As you see we have same function name but both has different parameter types and return types while both are used to add a and b;
1 2 3 4 5 6 7 8 9 10 11 |
int add (int a, int b) { return a+b; } float add (float a, float b) { return a+b; } |
Get started building powerful apps with C++Builder!
Design. Code. Compile. Deploy.
Start Free Trial
Free C++Builder Community Edition