user2841264
user2841264

Reputation: 19

Overload Function Call Operator in a Class

In the .h file given to me by my professor, he's written

    double operator()(double x) const;

The point of the overload is to read in x as a double and use it to evaluate a polynomial that's stored in the class object Term. What I've come up with in the class implementation is

    double operator()(double x) const
    {   double result = 0.0;
        for (int i = 0; i < getSize(); i++)
            result += (getCoeff(i) * pow(x, getExponent(i)));
        return result;
    }

How do I call it from the application? I've tried different calls like

    Polynomial p;
    p.operator(x);

or

    Polynomial::operator(x);

or

    operator(x);

but always get errors when compiling.

Upvotes: 1

Views: 1002

Answers (1)

juanchopanza
juanchopanza

Reputation: 227390

The usual form is to call it as if your instance was a function:

double x = 3.1416;
Polynomial p;
double y = p(x);

Alternatively, you can explicitly call the operator:

double x = 3.1416;
Polynomial p;
double y = p.operator()(x);

Here's a simplified example:

#include <iostream>

struct Foo
{
  double operator()(double x) const { return x*2; }
};

int main()
{
  Foo f;
  std::cout << f(2.5) << std::endl;
}

Upvotes: 4

Related Questions