2

I have a Button class:

class Button : public Component {

private:
    SDL_Rect box;
    void* function;

public:
    Button( int x, int y, int w, int h, void (*function)() );
    ~Button();
    void handleEvents(SDL_Event event);

};

And I want to execute Button::function in the method Button::handleEvents:

void Button::handleEvents(SDL_Event event) {
    int x = 0, y = 0;
    // If user clicked mouse
    if( event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) {
            // Get mouse offsets
            x = event.button.x;
            y = event.button.y;

            // If mouse inside button
            if( ( x > box.x ) && ( x < box.x + box.w ) && ( y > box.y ) && ( y < box.y + box.h ) )
            {
                this->function();
                return;
            }
    }

}

When I try to compile, I get the following errors:

Button.cpp: In the constructor ‘Button::Button(int, int, int, int, void (*)(), std::string)’:
Button.cpp:17:18: error: invalid conversion from ‘void (*)()’ to ‘void*’ [-fpermissive]
Button.cpp: In the function ‘virtual void Button::handleEvents(SDL_Event)’:
Button.cpp:45:19: error: can't use ‘((Button*)this)->Button::function’ as a function
Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130

4 Answers4

2

In your class variable declarations, you have

void* function;

This declares a variable named function which is a pointer to void. To declare it as a function pointer, you need the same syntax as that in your parameter list:

void (*function)();

This is now a pointer to a function which returns void.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
2

The function pointer in your private section is not declared as it should be.

It should be :

void (*functionPtr)();

Look at this question for more info.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
1

I suggest std::function<void()> for this kind of purpose:

#include <functional>

class Button : public Component
{
private:
    SDL_Rect box;
    std::function<void()> function;

public:
    Button( int x, int y, int w, int h, std::function<void()> f);
    ~Button();
    void handleEvents(SDL_Event event);
};

void Button::handleEvents(SDL_Event event)
{
    int x = 0, y = 0;
    // If user clicked mouse
    if( event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT)
    {
        // Get mouse offsets
        x = event.button.x;
        y = event.button.y;
        // If mouse inside button
        if( ( x > box.x ) && ( x < box.x + box.w ) && ( y > box.y ) && ( y < box.y + box.h ) )
        {
            function();
            return;
        }
    }
}
sehe
  • 374,641
  • 47
  • 450
  • 633
0

You might change the field declaration,

void * function; // a void ptr
void (*function)(); // a ptr to function with signature `void ()`

or use a cast:

((void (*)())this->function)();
vines
  • 5,160
  • 1
  • 27
  • 49