Function overloading in C++: Basic

Function overloading is an interesting concept and its very useful in some scenarios. So, what is function overloading? Function overloading means defining multiple functions with the same name which differ in either their parameter numbers, parameter types or both. Let's see an example to clear things out:
Let's say we want to define an add function. Depending on the type of its parameters, it'll return different values. For example, when you pass two integers 5 and 3 it'll return 8. When you pass 5.05 and 2.90 it'll return 7.95, when you pass two strings - "hello " and "world" it'll concatenate (join) them together and return "hello world". Here's how we do can do it -

#include <iostream>
using namespace std;

// add two 'int' and return their sum
int add(int a, int b) {
 return a + b;
}

// add two 'double' and return their sum
double add(double a, double b) {
 return a + b;
}

// concatenate (join) two 'string' and return the result
string add(string a, string b) {
 return a + b;
}

// this function just adds 5 to any number it is supplied
int add(int x) {
 return x + 5;
}

int main() {
 // this add(5, 3) will call the function at line 5
 cout << add(5, 3) << endl;

 // this add(5.05, 2.90) will call the function at line 10
 cout << add(5.05, 2.90) << endl;

 // this add("hello ", "world") will call the function at line 15
 cout << add("hello ", "world") << endl;

 // this add(10) will call the funciton at line 20
 cout << add(10) << endl;number

 return 0;
}

The output will be:

8
7.95
hello world
15

As you can see, depending on the type and/or number of arguments supplied, the compiler is smart enough to call the correct function.
Function overloading is also possible in the context of a class. You can have multiple overloaded functions as members of the same class. Not only that, even constructors can be overridden.

NOTE: Return type of a function is never taken into consideration in case of function overloading. Always keep that in mind.

No comments:

Post a Comment

Power function

In C/C++ (and also other languages), we have the built in power function to raise a number to a given power. What if we need to calculate ...