I have an abstract class an I like to know if it's possible to define an abstract function with variable arguments list?
Give me an example if it's possible.
Abstract methods can only have names and arguments, and no other code. Thus, we cannot create objects out of abstract classes.
A variable argument function (variadic function) is a function that can accept an undefined number of arguments. In many programming languages, formatted output functions are defined as variadic functions. In C++, variable argument functions are declared with the ellipsis (...) in the argument list field.
To call a function with a variable number of arguments, simply specify any number of arguments in the function call. An example is the printf function from the C run-time library. The function call must include one argument for each type name declared in the parameter list or the list of argument types.
Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.
Yes, it is possible in principle. An example follows below. You can see the output here.
Also read about variable arguments list here and here
#include <iostream>
#include <cstdarg>
using namespace std;
class AbstractClass{
public:
virtual double average(int num, ... ) = 0;
};
class ConcreteClass : public AbstractClass{
public:
virtual double average(int num, ... )
{
va_list arguments; // A place to store the list of arguments
double sum = 0;
va_start ( arguments, num ); // Initializing arguments to store all values after num
for ( int x = 0; x < num; x++ ) // Loop until all numbers are added
sum += va_arg ( arguments, double ); // Adds the next value in argument list to sum.
va_end ( arguments ); // Cleans up the list
return sum / num; // Returns the average
}
};
int main()
{
AbstractClass* interface = new ConcreteClass();
cout << interface->average( 3 , 20 ,30 , 40 );
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With