Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class member pointer to global function

I want to have a class which has as a member a pointer to a function

here is the function pointer:

typedef double (*Function)(double);

here is a function that fits the function pointer definition:

double f1(double x)
{
    return 0;
}

here is the class definion:

class IntegrFunction
{
public:
    Function* function;
};

and somewhere in the main function i want to do something like this:

IntegrFunction func1;
func1.function = f1;

But, this code does not work.

Is it possible to assign to a class member a function pointer to a global function, declared as above? Or do I have to change something in the function pointer definition?

Thanks,

like image 207
Alina Danila Avatar asked May 14 '11 21:05

Alina Danila


3 Answers

Replace this:

class IntegrFunction
{
public:
    Function* function;
};

with this:

class IntegrFunction
{
public:
    Function function;
};

Your typedef already creates a pointer-to-function. Declaring Function* function creates a pointer-to-pointer-to-function.

like image 84
Robᵩ Avatar answered Sep 21 '22 21:09

Robᵩ


Just replace

Function* function;

to

Function function;
like image 36
Slava Semushin Avatar answered Sep 23 '22 21:09

Slava Semushin


You declare the variable as Function* function, but the Function typedef is already a typedef for a pointer. So the type of the function pointer is just Function (without the *).

like image 36
Christian Rau Avatar answered Sep 21 '22 21:09

Christian Rau