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.