1

I'm trying to make a code that find the numerical derivation of a function. I also have a polynomial class described as follows:

    class polynomial
    {
    public:
        polynomial(Vector, int);
        polynomial();
        ~polynomial();

        double returnValue(double);
        void print();

    private:
        int Degree;
        Vector Coeficients;
    };

my numerical derivation have the following prototype:

 double numericalDerivation( double (*F) (double), double x);

I want to pass the returnValue method into the numericalDerivation, is that possible?

  • No. `returnValue` isn't a function, i.e. you cannot *call* it. Search this site for hundreds of duplicates on how to deal with member function pointers. – Kerrek SB Feb 19 '13 at 01:44
  • Actually, `returnValue` is a function, but a member function. `numericalDerivation` expects a function pointer, not a member function pointer (that would be a different type). – jogojapan Feb 19 '13 at 01:49

1 Answers1

0

Yes, it is possible, but don't forget it is a member function: you won't be able to call it without having a (pointer to) an object of type polynomial on which to invoke it.

Here is how the signature of your function should look like:

double numericalDerivation(double (polynomial::*F)(double), polynomial* p, double x)
{
    ...
    (p->*F)(x);
    ...
}

Here is how you would invoke it:

double d = ...;
polynomial p;
numericalDerivation(&polynomial::returnValue, &p, d);

Alternatively, you could use an std::function<> object as a parameter of your function, and let std::bind() take care of binding the object to the member function:

#include <functional>

double numericalDerivation(std::function<double(double)> f, double x)
{
    ...
    f(x);
    ...
}

...

double d = ...;
polynomial p;
numericalDerivation(std::bind(&polynomial::returnValue, p, std::placeholders::_1), d);
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451