Computer Science: Function: Function Overloading: Two or More Functions Parameters

Get unlimited access to the best preparation resource for IAS/Mains/Optional Political-Science: fully solved questions with step-by-step explanation- practice your way to success.

Download PDF of This Page (Size: 221K)

Image shows function overloading

Image Shows Function Overloading

Function Overloading

  • This means that some function name can be used to create functions that perform a variety of different tasks.

  • This is known as function polymorphism in OOP.

  • The function would perform different operations depending on the argument list in function call.

  • The correct function to be invoked is determined by checking the number and type of arguments.

For example, an overloaded function mpy () handles different types of data as follows:

/ / Declaration

void mpy (int, int); / / prototype 1

void mpy (int, float); / / prototype 2

void mpy (float, int); / / prototype 3

void mpy (float, float); / / prototype 4

/ / Function calls

cout < < mpy (3.5, 1.2); / / uses prototype 4

cout < < mpy (2, 5); / / uses prototype 1

cout < < mpy (5.2, 6); / / uses prototype 3

cout < < mpy (7, 6.2); / / uses prototype 2

  • A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution.

  • A best match must be unique.

The function selection involves the following steps:

  • The compiler tries to find an exact match in which types of actual arguments are the same and use that function.

  • If an exact match is not found, the compiler uses the integral promotions to the actual arguments, such as

char to int

float to double

to find a match.

  • When either of them fails, the compiler tries to use the built-in conversions (the implicit conversions) to the actual arguments then uses the function whose match is unique. If the conversion is possible to have multi matches, then the compiler will generate an error message. Suppose we use the following two functions: -

long abc (long n).

double abc (double x).

A function call such as

abc (10)

will cause an error because int argument can be converted to either long or double, thereby creating an ambiguous situation.

  • If all the steps fail, then the compiler will try the user defined conversions in combination with integral promotions and built in conversions to find a unique match.

Developed by: