
 |
![]() |
|
|
|
|
 |
Overloading Functions
When you overload a function, you use the same name but you must use different parameters. If you don’t the compiler won’t know that they are different functions. Here is the syntax on how to overload a function:
it’s the exact same as creating a regular function. Except you would create more then one function that uses the same name. For instance:
 | |  | | |
int Add(int,int,int);
int Add(int,int);
int Add(int,int,int,int); |
|  |
|
this would create three functions that all have the same name, but add a different amount of numbers based on the parameters entered. As long as the functions have a different amount of parameters or a different return type things will work out fine
Here is an application I created to show the use of function overloading
 | |  | | |
//tq.h
//example of overloading a function
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
int add(int a, int b, int c, int d)
{
return a+b+c+d;
}
|
|  |
|
As you can see I used the same functions as in the above example. These three functions add the numbers entered and return the result.
Here is the main.cpp
 | |  | | |
#include <iostream.h>
#include "tq.h"
//function prototypes
int add(int,int);
int add(int,int,int);
int add(int,int,int,int);
int main()
{
int a, b, c, d;
int result;
char choice = 0;
cout <<"Choose: (1), (2), (3)";
cin >> choice;
switch(choice)
{
case '1': cout <<"Enter 2 numbers: ";
cin >> a >> b;
result = add(a,b);
break;
case '2': cout <<"Enter 3 numbers: ";
cin >> a >> b >> c;
result = add(a,b,c);
break;
case '3': cout <<"Enter 4 numbers: ";
cin >> a >> b >> c >> d;
result = add(a,b,c,d);
break;
default: cout <<"An Error has occuredn";
break;
}
cout <<"result: " << result << endl;
return 0;
}
|
|  |
|
I used the switch statement to let the user choose which function they wish to use. If the user entered the number 1, it would prompt the user to enter two numbers. By entering these two numbers it calls the function:
If the user entered the number 2, it would prompt the user to enter 3 numbers. Which then calls on the function:
and so on. I think you got the drift of how function overloading is handled. We will be getting into more advanced overloading once you get to Inheritance and Polymorphism sections of the site.
Please Rate this Code:
|
|
|
|
|
|
|