I’m trying to teach myself some C++ and as an initial project, I want to create code for performing Newton’s method on functions of a single variable. I want to make a class ObjectiveFunction that stores user-defined functions for the objective function, the first derivative, and the second derivative.
I want the constructor of ObjectiveFunction to take between 0 and 3 arguments, where the arguments themselves are functions:
// ObjectiveFunction.h
// Class definition for an Objective Function object.
#ifndef OBJECTIVE_H
#define OBJECTIVE_H
class ObjectiveFunction
{
public:
// Constructors
// Default constructor
ObjectiveFunction();
// Constructor with just objective function.
ObjectiveFunction(double f(double));
// Constructor with objective function and derivative function.
ObjectiveFunction(double f(double), double fp(double));
// Constructor with objective, derivative, and second derivative functions.
ObjectiveFunction(double f(double), double fp(double), double fpp(double));
// Methods
void setObjectiveFunction(double f(dobule));
void setDerivativeFunction(double f(double));
void setSecondDerivativeFunction(double f(double));
double evalObjectiveFunction(double);
double evalDerivativeFunction(double);
double evalSecondDerivativeFunction(double);
private:
// Storage for the functions.
// This is the part I'm not sure of.
// Attempt with function pointers
double (*objFunc)(double);
double (*d1Func)(double);
double (*d2Func)(double);
};
#endif // OBJECTIVE_H
How would I create private data members that themselves are functions. I want to create functions objects that (except for being private) would be accessible like foo.obj_func(3.0) or foo.deriv_func(3.0), where obj_func gets set by the constructor based on the functions that the user passes to the class.
What is the right way to do this? It would be best if there is a way that does not rely on using a pointer to a function object, but I guess if that’s the only way then it’s what I’ll have to learn.
Use
std::function<double(double)>. This will enable you to store all function types easily.