0

In one of my methods, a function with two parameters is passed, and saved as rightClick. However, because its in a static function, the compiler wants the function to be initialised before. How can i go about this?

Mouse.cpp

void Mouse::clicked(int button, int state, int x, int y)
{
    if(button == GLUT_LEFT_BUTTON) {
        if(state == GLUT_DOWN) {
            isDragging = true;
            CurrentX = x;
            CurrentY = y;
        }
        else
        {
            isDragging = false;
        }
    }
    else if (button == GLUT_RIGHT_BUTTON)
    {
        if (state == GLUT_DOWN)
        {
            isDragging = true;
            rightClick(x,y);
        }
    }

}

void Mouse::setRightClickFunction(void (*func)(int, int))
{
    rightClick = func;
}

The setRightClickFunction is called before click ever is. Except now i'm getting a different problem : "Mouse::rightClick", referenced from: Mouse::clicked(int, int, int, int) in Mouse.o

10
  • 1
    Do you mean that setRightClickFunction is static and if so, why? If not, what function does the compiler wants initialized, exactly? Commented Sep 16, 2013 at 12:06
  • 1
    Pass a valid function (global, in namespace, or static member function) as argument to the setRightClickFunction function, before the clicked handler is called. Commented Sep 16, 2013 at 12:06
  • You might also want to read about std::function and std::bind. Commented Sep 16, 2013 at 12:06
  • 2
    Can you provide the exact compiler error? Commented Sep 16, 2013 at 12:07
  • 1
    @DuskFall a typedef would simplify things. I'll leave Angew to write up the answer if he want's, he would have told you the same thing. Commented Sep 16, 2013 at 12:27

1 Answer 1

2

Based on your comments, you're getting a linker error about "undefined reference to Mouse::rightClick. This has nothing to do with function pointers. It's just that whenever you declare a static data member in a class, it's only a declaration. You have to define it somewhere (= in exactly one .cpp file).

Assuming your class Mouse looks something like this:

class Mouse
{
  //...
  static void (*rightClick)(int, int);
  //...
};

You should put this line somewhere into Mouse.cpp:

void (*Mouse::rightClick)(int, int) = 0;

That will serve as the definition of the static data member rightClick.

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

Comments

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.