Function Overloading

As stated earlier, overloading refers to the use of the same thing for different purposes. C++ also permits overloading of functions. This means that we can use the same function name to create functions that perform a variety of different tasks. This is known as function polymorphism in OOP.

Using the concept of function overloading; we can design a family of functions with one function name but with different argument lists. The function would perform different operations depending on the argument list in the function call. The correct function to be invoke is determine by checking the number and type of the arguments but not on the function type. For example, an overload add() function handles different types of data as shown below:

// Declarations
int add(int a,int b);
int add(int a,int b,int c);
double add(double x,double y);
double add(int p,double q);
double add(double p,int q);

// Function calls
cout << add(5,10);
cout << add(15,10.0);
cout << add(12.5, 7.5);
cout << add(5,10,15);
cout << add(0.75,5);

No comments:

Post a Comment