Function overloading is a concept where several function declarations are specified with a single and a same function name within the same scope. Such functions are said to be overloaded. C++ allows functions to have the same name. Such functions can only be distinguished by their number and type of arguments.

Example:

The function divide(), which takes two integer inputs, is different from the function divide() which takes two float inputs.

What is the need for function overloading?

Every object has characteristics and associated behavior. An object may behave differently with change in its characteristics. Therefore, in order to simulate real world objects in programming environment, it is necessary to have function overloading.

For Example:

Function overloading not only implements polymorphism but also reduces number of comparisons in a program and thereby making the program run faster.

How to implement function overloading?

The key to function overloading is the function's argument list which is also known as function signature. It is the signature and not the function type that enables function overloading.

If two functions have the same number and type of arguments in the same order, they are said to have the same signature.

Both these functions have the same signature.

Sample for Function Overloading

C++ allows you to overload a function provided the function has the same name but different signatures. The signature can differ in the number of arguments or in the type of arguments, or both. To overload a function, all you need to do is, declare and define all the functions with the same name but different signatures.

Example:

When a function, with same name, is declared more than once in the program, the compiler will interpret the second declaration as follows:

  • If the signature of subsequent function matches the previous function, then the second is treated as the re-declaration of the first.
  • If the signature of both the functions match exactly, but the return type differs, then the second declaration is treated as an erroneous re-declaration of the first and is flagged at compile time as an error.

For example,