A. Saksena said:
Does it also work for user defined data types and classes
Please don't top-post. Rearranged.
If you are talking about variable-argument function (also called
variadic functions), yes it does, but you need to understand why.
When you don't specify the exact count of argument, you can obviously
not specify their type. Take my example again:
void f(int n ...)
{
// ...
}
int main()
{
f(3,1,2,3);
}
In this case, since you did not specify the all the arguments for f(),
the compiler cannot check if the types correspond. That means
void f(int n, ...)
{
va_list vl;
va_start(vl, n);
int my_int = va_arg(vl, int); // we are assuming its an int
std::cout << my_int;
va_end(vl);
}
int main()
{
double d = 10.5;
f(1, d); // we're passing a double
}
will compile with no error. That does not mean there are none. As you
see in f(), I converted the first argument of the list to 'int', but the
actual type I passed was a double. Problem.
class C
{
// ..
};
int main()
{
C c;
f(1, c); // ouch!!
}
The thing is, f() has *absolutely* no ways of knowing what type of
argument it received. That's why we usually use the first argument as a
string to be able to specify what are the remaining arguments.
printf("%s %d", "test", 10);
By the way, printf() looks like
int printf(const char* ...);
In this case, printf() will know, by looking at the string, that the
types of the arguments are char* and int because of the tokens %s and
%d. Beware if you did not pass the correct arguments.
So variadic functions are not for the faint of heart. It is extremely
easy no to give correct arguments to such a function. There are other
ways to do that. Explore them.
As I said before, default arguments might be of help or even a class
with a collection inside (or a plain collection such as a std::vector).
For us to be able to help you more, you should explain what you are
trying to do.
Jonathan