Best Way to Have a Pointer to Several Methods in C++ – Code Critique

cmethodspointers

I'm starting with a short introduction of what I know from the C language:

  • a pointer is a type that stores an adress or a NULL
  • the * operator reads the left value of the variable on its right and use this value as address and reads the value of the variable at that address
  • the & operator generate a pointer to the variable on its right

So I was thinking that in C++ the pointers can work this way too, but I was wrong. To generate a pointer to a static method I have to do this:

#include <iostream>

class Foo{
    public:
    static void dummy(void){ std::cout << "I'm dummy" << std::endl; };
};

int main(){
    void (*p)();
    p = Foo::dummy; // step 1
    p();
    p = &(Foo::dummy); // step 2
    p();
    p = Foo; // step 3
    p->dummy();
    return(0);
}

Now I have several questions:

  • Why does step 1 work?
  • Why does step 2 work too? Looks like a "pointer to pointer" for p to me, very different from step 1.
  • Why is step 3 the only one that doesn't work, and is the only one that makes some sort of sense to me, honestly?
  • How can I write an array of pointers or a pointer to pointers structure to store methods (static or non-static from real objects)?
  • What is the best syntax and coding style for generating a pointer to a method?

Best Answer

what is the best syntax and coding style for generating a pointer to a method?

Don't. Use std::function<void()>.

Now, on to the steps. Step 1 is technically illegal, but your compiler allowed it by implicitly taking the address for you. Step 2 is how it should be done. The name of a static function (in this case, Foo::dummy) is a function lvalue and must have it's address taken to be legal C++ and yield a function pointer.

Step 3 simply doesn't make any sense at all. You're trying to assign ... a run-time function pointer ... to a type? That makes no sense whatsoever. And then you try to access ... a member ... of a function pointer? Does not compute.

There are two parts to the answer "What do I do when I want to X in C++?". The first part, for C veterans only, is "Forget whatever you think you learned in C". The second part is about doing X.

how can i write an array of pointers or a pointer to pointers structure to store methods ( static or non-static from real objects )

std::vector<std::function<void()>> arr;

le done.