Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract functions and variable arguments list

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.

like image 844
Forro Istvan Avatar asked Feb 21 '12 11:02

Forro Istvan


People also ask

Can abstract methods have arguments?

Abstract methods can only have names and arguments, and no other code. Thus, we cannot create objects out of abstract classes.

What is variable argument function?

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.

How do you write a function with variable number of arguments?

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.

What are variable arguments or Varargs?

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.


1 Answers

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;
}
like image 187
Aman Aggarwal Avatar answered Sep 29 '22 18:09

Aman Aggarwal