In the following program I’ve a function overloading. One with just a single argument, another with two arguments and another with three. In the following example it looks simple because the function is not too long. What if the function is very long and it looks ugly to write the same function again and again with different input arguments. One way to do that can be variadic functions. If I know that my function is going to take only 1,2 or 3 input arguments is variadic functions really necessary ? If so how can I do that ? Note : the function with three input args and two input args perform different calculations.
#include <iostream>
using namespace std;
int function(int a, int b, int c) // All the arguments are always of the same type
{
return a*b*c;
}
int function(int a, int b)
{
int c = a; // Always duplicate the first argument
return a*b*c;
}
int function(int a)
{
int b = a, c = a; // Always duplicate the first argument
return a*b*c;
}
int main()
{
cout<<function(2,3,4)<<"\n"<<function(2,3)<<"\n"<<function(2);
cin.ignore();
return 0;
}
EDIT:
Sorry for the ambiguity guys. I edited the code.
First of all if your function is long and ugly you should refactor it into a set of smaller functions or even classes.
As to your actual question, I would use the overloaded functions as wrappers like this:
This avoids code duplication and any need for a variadic function. With variadic functions you lose the static type checking, so they are very error prone.