Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Assigning function pointer to another

Tags:

c++

pointers

I want to do a class that stores function pointers, but when I want to store them in member variables I get this error:

invalid use of member function (did you forget the '()' ?)

¿Where is my error?

class Button {
public:
    Button(PS3USB * ps3, ButtonEnum button, void (*onPress)(void) = nullptr,
            void (*onRelease)(void) = nullptr) {
        PS3 = ps3;
        status = false;
        ERROR --->  onPressFunction = onPress; <--- ERROR
        ERROR --->  onReleaseFunction = onRelease; <--- ERROR
        id = button;
    }
    void check() {
        if (PS3->getButtonClick(id) && !status) {
            if (onPressFunction != nullptr) {
                onPressFunction();
            }
            status = !status;
        } else if (!PS3->getButtonClick(id) && status) {
            if (onReleaseFunction != nullptr) {
                onReleaseFunction();
            }
            status = !status;
        }
    }
private:
    bool status;
    PS3USB * PS3;
    ButtonEnum id;
    void * onPressFunction(void);
    void * onReleaseFunction(void);

};

Thanks

like image 674
Oscar Garcia Lorenz Avatar asked Sep 05 '16 12:09

Oscar Garcia Lorenz


People also ask

What is the correct way to declare and assign a function pointer?

Function Pointer Syntaxvoid (*foo)( int ); In this example, foo is a pointer to a function taking one argument, an integer, and that returns void. It's as if you're declaring a function called "*foo", which takes an int and returns void; now, if *foo is a function, then foo must be a pointer to a function.

Can pointers point to functions?

A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions.


2 Answers

void * onPressFunction(void);
void * onReleaseFunction(void);

These are declarations of a member functions, not a function pointer. To declare pointers to function instead use:

void (*onPressFunction)(void);
void (*onReleaseFunction)(void);
like image 135
Sergio Avatar answered Nov 12 '22 12:11

Sergio


void * onPressFunction(void);
void * onReleaseFunction(void);

These above do not declare a function pointer, but they create a member function each returning a pointer to a void, I think you meant this:

void (* onPressFunction)(void);
void (* onReleaseFunction)(void);

Also, for function pointers, I would recommend you use typedefs, or std::function

Typedef Example

typedef void(*onReleaseFunction)(void);

And it could be used like this:

onReleaseFunction func = &functionname;
like image 32
Arnav Borborah Avatar answered Nov 12 '22 11:11

Arnav Borborah