Population Xplosive
Population Xplosive

Reputation: 617

function pointer - inside and outside a class

I'm a noob to function pointers and this is the first time I'm using it.

The code is:

#include "time.cpp"
int main(){
 double** matrix= new double*[10];
 for (int i=0; i<10; i++) matrix[i]=new double[10];
 gear nit;
 nit.roll(&matrix[0]);
}

time.cpp

double pulse_a (double t, double dt);

class gear{
        void dynamics(double (*)(double, double), double** , double, double);
        double pulse_b(double t, double dt);
public:
        int net;
        void roll(double** matrix);
};

void gear::roll(double** matrix){
        double t,dt;
        double (*pfunc)(double,double)=pulse_a; //or pulse_b
        dynamics(pfunc,&matrix[0],t,dt);
}

void gear::dynamics(double (*pulse)(double , double ), double** matrix, double t, double dt){

pulse(t,dt);
}

When I assign pfunc to pulse_a, I get

error: argument of type ‘double (gear::)(double, double)’ does not match ‘double (*)(double, double)’

for double (*pfunc)(double,double)=pulse_a;

When I assing pfunc to pulse_b, I get undefined reference to chirp(double, double)' for double (*pfunc)(double,double)=pulse_b;

What am I doing wrong?

Upvotes: 0

Views: 992

Answers (2)

Beta
Beta

Reputation: 99094

You have chosen a ridiculously complicated example for your first foray into function pointers. You should start with the simplest example you can come up with.

Your first pointer

double (*pfunc)(double,double)=pulse_a;

works as written. It doesn't produce the error you describe; I don't see how it could possibly produce the error you describe (since it doesn't involve gear), so I'll bet the code you posted is not the code that produced the error. Please don't do that.

A pointer to a function and a pointer to a member function are different animals. They have different types and are not interchangeable. Don't try to cast one to another or you'll be in violation of ancient tribal law (and you'll get undefined behavior).

void dynamics2(double (gear::*)(double, double), double** , double, double);
...
double (gear::*pfunc2)(double,double) = &gear::pulse_b;
dynamics2(pfunc2,&matrix[0],t,dt);

Once you've gotten the hang of these pointers, you can save yourself some headaches by means of typedef:

typedef double (gear::*gearMemFn)(double, double);
void dynamics2(gearMemFn, double** , double, double);
...
gearMemFn pfunc2=&gear::pulse_b;

Upvotes: 3

Puppy
Puppy

Reputation: 146910

Don't use function pointers for anything. Use std::function like a normal person.

Also, member functions are not and can never be function pointers. It will have to be a static function.

Upvotes: 0

Related Questions