8

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.

2 Answers 2

31

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;
Sign up to request clarification or add additional context in comments.

3 Comments

'somewhat', he declares modestly!
+1 for typedeffing function pointers. (ppl who don't ought to be shot, IMHO ;)
Thanks, it helped me really much too! It's pitty I can't mark this post twice.
12
void (*A::cb)(int a, char c) = NULL;

3 Comments

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.
@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, 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.