views:

94

answers:

2

I have a member function in a class that has a callback, but the callback isn't strictly neccessary, so it has a default callback, which is empty. It seems to work fine, but I get an annoying warning:

warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’

I'm trying to figure out what it means and how to turn it off (or fix it if I really am doing something wrong). Here's some simple code:

class ClassName{
public:
    void doSomething(void (*callbackFunction)() = (void(*)()) &ClassName::doNothing){
        callbackFunction();
    }
    void doNothing(){}
};

int main(){
    ClassName x;
    x.doSomething();
    return 0;
}

Note: If I do this (without explicitly casting it as a void(*)()):

void doSomething(void (*callbackFunction)() = &ClassName::doNothing)

I get this:

main.cpp:3: error: default argument for parameter of type ‘void (*)()’ has type ‘void (ClassName::*)()’
+4  A: 

The issue is that you're passing a pointer to an instance method rather than a static method. If you make doNothing a static method (which means no implicit instance argument), the warning goes away.

Specifically,

warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’

exactly is saying that it's converting from a member function of class ClassName, to a non-member function.

See also the C++ FAQ Lite entry about pointers to member functions and pointers to functions.

Mark Rushakoff
Ohhh. I should've thought to make it static. Thanks.
Brendan Long
+1  A: 

Free function pointer is not the same as class member function pointer, which requires an instance of the class at call site. Though a static member function will do.

Nikolai N Fetissov