Function Overloading
Function Overloading is used when we need to handle parameters of different data types. Function Overloading refers to having different function with same name. The functionality of that function is then defined according to the type of parameters given.
For example:
void add(int a, int b) {
cout<<a+b;
}
int main() {
add(24.42, 76.98);
}
//Outputs : 100
The above function will not give expected output as we have provided float or decimal value to the function requiring int as parameters. To cope with this problem we can define a new function with the same name but double values as the data type of parameters.
#include <iostream>;
using namespace std;
void add(int a, int b) {
cout<<"Doing integer sum"<<endl;
cout<<a+b;
}
void add(double a, double b) {
cout<<"Doing decimal sum"<<endl;
cout<<a+b;
}
int main() {
add(24,76);
add(24.42, 76.98);
}
/* Output:
Doing integer sum
100
Doing decimal sum
101.4 */
Here the compiler decide on itself about which function to use and gives the desired output. Thus different data types can be handled form same function name. There is an better way to solve the problem of different types of parameters which I’ll be discussing soon.
Recursion
In the examples above, we were calling the function through the main(). A function can be called from other function too or sometimes it can call itself. When a function calls itself, it is known as Recursion. The benefit of using recursion is that it is very simple to define, understand and look at. The recursion do the same work as loops but sometimes to decrease the difficulty of code recursion is used. Here is an example of recursion:
#include <iostream>
using namespace std;
int factorial(int a)
{
if (a == 0){
return 1;
}
else{
return a*factorial(a-1);
}
}
int main() {
cout<<factorial(4);
}
//Outputs : 24
The factorial of a number n is n(n-1)(n-2)….1. i.e. product of the number with all the natural numbers before it. We can define it using loops by looping over all values from 1 to that number. Another method is to use recursion. As we know that factorial(n) = n*factorial(n-1) and factorial(1) is 1. Thus for every value of n greater than 1 we can use the above formula and call the function again.
The most important thing in a recursive function is that it should necessarily contain a base condition. The base condition serves as the stopping point for the function. Without a proper base condition the recursion will run forever leading to errors.
With the help of recursion we can break complex problem into simpler steps and make it easier to understand.
