6

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,

3
  • In what way does it not work? Commented May 14, 2011 at 21:58
  • How does it "not work"? Do you get a compiler error? If so, what is it? Commented May 14, 2011 at 21:58
  • The answer might be easier for us to find if you would supply a complete example. You are so close, it would only take just a few more lines to make it complete. Also, can you tell us what you mean by "does not work?" Do you get an error from the compiler? Linker? Do you get a run-time behavior different than what you expect? Commented May 14, 2011 at 21:59

5 Answers 5

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I understood my mistake and my code works now. I should be more careful next time.
4

Just replace

Function* function;

to

Function function;

Comments

2

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 *).

Comments

0

Replace

typedef double (*Function)(double);

by

typedef double Function(double);

to typedef the function-type. You can then write the * when using it.

Comments

-3

You need to use the address-of operator to obtain a function pointer in Standard C++03.

func1.function = &f1;

1 Comment

No you don't. The & is necessary for taking the address of a member function but not for a nonmember function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.