views:

337

answers:

2

I cannot figure the syntax to declare a function pointer as a static member.

#include <iostream>
using namespace std;

class A
{
    static void (*cb)(int a, char c);
};

void A::*cb = NULL;

int main()
{
}

g++ outputs the error "cannot declare pointer to `void' member". I assume I need to do something with parentheses but void A::(*cb) = NULL does not work either.

+5  A: 
void (*A::cb)(int a, char c) = NULL;
Goz
That's something different: It's a member function pointer.
Johannes Schaub - litb
hehe ... works on my machine ;)
Goz
I fixed it anyway.
Goz
Good :) It's not that your previous answer was doing the same. It was correct code, but it wasn't defining the static member. Instead it was defining a global member-function pointer.
Johannes Schaub - litb
@litb: No, 'void (A::*cb)(int a, char c)' would be a member function pointer, if I understand correctly what you mean by 'member function pointer' (multi-word terms are quite ambiguous in C++)
AndreyT
@AndreyT, what does your "No" refer to? I was saying that his member pointer definition was correct (and thus "worked" for him), but that it wasn't defining the static function pointer member of "A" (instead of was defining a totally unrelated thing, as you point out too). In response to his edit, i deleted my answer and retracted my downvote (which i casted after he said "hehe... works on my machine."). I agree that the terms are slightly ambiguous, but the code isn't. In this sense, i don't understand what your "No" refers to.
Johannes Schaub - litb
+13  A: 

I introduced a typedef, which made it somewhat clearer in my opinion:

class A
{
  typedef void (*FPTR)(int a, char c);

  static FPTR cb;
};

A::FPTR A::cb = NULL;
Kim Gräsman
'somewhat', he declares modestly!
xtofl
Well, I try! :)
Kim Gräsman
+1 for typedeffing function pointers. (ppl who don't ought to be shot, IMHO ;)
Marcus Lindblom
Thanks, it helped me really much too! It's pitty I can't mark this post twice.
MInner