what is function overloading in c++ with example

what is function overloading in c++ with example

1 year ago 41
Nature

Function overloading is a feature in C++ that allows multiple functions to have the same name but different parameters. This feature is used to improve code readability and to save the programmer from having to memorize different function names. Function overloading can be considered as an example of a polymorphism feature in C++ .

The rules for overloading functions in C++ are as follows:

  • We can have more than one function with the same name in the same scope.
  • The parameter list of the functions should be different.
  • The return type of the functions may or may not be different.

Here is an example of function overloading in C++ :

#include <iostream>
using namespace std;

// function with float type parameter
float absolute(float var){
    if (var < 0.0)
        var = -var;
    return var;
}

// function with int type parameter
int absolute(int var) {
    if (var < 0)
        var = -var;
    return var;
}

int main() {
    cout << absolute(-5) << endl;
    cout << absolute(-5.5f) << endl;
    return 0;
}

In this example, two functions named absolute are defined with different parameter types. One function takes an int parameter and the other takes a float parameter. The function that is called depends on the type of the argument passed during the function call.

Function overloading can also be used with pointers and references. However, it is important to note that overloading a function with only a difference in return type is not allowed.

Read Entire Article