0

I want to make a class Function that can take a float method and use it to produce useful values from the function. However, I do not understand how to declare a private method inside the constructor as the method passed by argument.

Hopefully this class can help in understanding my intentions:

#include <iostream>
#include <math.h>


class Function {
    float function(float x);
    public:
        Function(float method(float)) {
            // how do I set private function "function" equal to passed function "method"?
        };
        float eval(float x) {
            return function(x);
        }
        float derive(float x, float error = 0.001) {
            return (function(x) - function(x + error)) / error;
        }
        float integrate(float x0, float x1, float partitions = 100) {
            float integral = 0;
            float step = (x1 - x0) / partitions;
            for(float i = 0; i < partitions; i += step) integral += step * function(i);
            return integral;
        }
};


float exampleFunction(float x) {
    return 2 * pow(x, 2) + 5;
}


int main() {
    Function myFunction (exampleFunction);

    std::cout << myFunction.eval(6);
}

Addressing possible duplicate:

The tagged question was asking about invoking the constructor using a pointer to a method in an already constructed instance of the class. I am trying to pass a pointer into a constructor to define the new class's private method.

  • you mean [function pointer](https://stackoverflow.com/questions/1485983/calling-c-class-methods-via-a-function-pointer?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa)? – Joseph D. May 10 '18 at 03:49
  • Possible duplicate of [Calling C++ class methods via a function pointer](https://stackoverflow.com/questions/1485983/calling-c-class-methods-via-a-function-pointer) – Joseph D. May 10 '18 at 03:50
  • I could pass by reference with `Function( float (*method)(float))`, but unless I can somehow pass that reference to `function`, I haven't fixed my issue. – Benjamin Brownlee May 10 '18 at 03:52

2 Answers2

2

Use

  // The member variable that stores a pointer to a function.
  float (*function)(float);

  // The constructor.
  // Store the passed function in the member variable.
  Function(float method(float)) : function(method) {}

Working demo.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Easier with typedef:

using func_t = float(float);

class Function {
    func_t* function = nullptr;
public:
    Function(func_t* f) : function(f) {}
    // ...
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302