chaviaras michalis
chaviaras michalis

Reputation: 364

Return a function pointer from a class member function

I have the class AbstractOdeSolver which is the following :

class AbstractOdeSolver
{
private:
    double (*rightHandSide)(double y,double t);

public:
    AbstractOdeSolver(int nop,double initime, double fintime, double initval, double(*pf)(double,double));
    double (*GetRightHandSide)(double y, double t)();
};

So I have a class with a private member a function pointer namely rightHandSide and I want to return it from a member function. So ...

  1. I don't know if the last line of the code define what I want to define, but I write having in thought this answer Returning function pointer type.

  2. If the last line is right then I want to know how can I write the implementation in the AbstractOdeSolver.cpp? I tried:

    double (*AbstractOdeSolver::GetRightHandSide)(double y, double t)()
    

    but this is not accepted even from the editor(Kdevelop) and I think with a small revision it is referred to something-like pointer to a member function not to a pointer to a function.

Note that I want to return a pointer to a function which take two doubles and returns a double, if it cannot be done it is ok.

Upvotes: 1

Views: 1096

Answers (1)

user2807083
user2807083

Reputation: 2972

IIUC what do you want, the most simple way is use typedef:

class AbstractOdeSolver 
{
public:
    typedef double (*FSolver)(double, double);
    ....
    FSolver GetRightHandSide();
};
....
AbstractOdeSolver::FSolver AbstractOdeSolver::GetRightHandSide()
{ 
    // just for an example:
    return +[](double, double) -> double { return 0.0; }    
}

The same without typedef:

class AbstractOdeSolver
{
public:
    double (* GetRightHandSide())(double, double);
};

double (*AbstractOdeSolver::GetRightHandSide())(double, double)
{
    return +[](double, double) -> double {return 0.0; };
}

And with trailing return type as suggested by @Jarod42:

class AbstractOdeSolver
{
public:
    auto GetRightHandSide() -> double (*)(double, double);
};

auto AbstractOdeSolver::GetRightHandSide() -> double (*)(double, double)
{
    return +[](double, double) -> double {return 0.0; };
}

Upvotes: 1

Related Questions