Function Overloading

Function overloading is the process of using the same function name for multiple functions, but using different parameters in the function call.

 

This allows the correct function to be called depending on the parameters sent.

 

Consider a function to add two numbers:

This is fine for two integers, but what if we wanted to add floating point pumbers? The precision would be lost.

 

We can create another function to add two floating point numbers:

But how does the compiler know which version of the add() function to use? The answer lies in how the add() function is called.

 

Basically, it depends on the context, inasmuch as the arguments used in the call.

 

Following on from the above code samples, if two ints are provided then the compiler will know that we mean to call the add(int a, int b) function, and consequently if we provide two floatinf point numbers the compiler will know that we mean to call the add(double a, double b) function.

 

add( 5, 7) ; //will call the add(int a, int b) function

 

add(3.141, 2.714) ; //will call the add(double a, double b) function

 

We could go on and define multiple add functions, and each would be called independently as long as each add() function has unique parameters, e.g. three ints, or two ints and a double, etc.

Leave a Reply