Hi again everybody.

I know there are some references to this kind of thing around the web but none of them are simple enough for me to understand.

In my code below, I am trying to initialize a function pointer with a class member function but I'm not sure I understand how.

For simplicity my function pointer "myfunction" is to be initialized with myclass::class_function.
How do I do this?

Thank you.

#include <iostream>
#include <cstdlib>


using namespace std;



class myclass
{
    public:
    void class_function()
    {
        cout << "Class Function Called" << endl;
    }

};


int main()
{
  void(*myfunction)();



myclass cls;

   myfunction = cls.class_function; // I get an error here. 
           //C:\CodeBlocksFiles\All\FunctionPointers\main.cpp:31:15: error: cannot convert 
           //'myclass::class_function' from type 'void (myclass::)()' to type 'void (*)()'

  system("pause>nul");
}

It's very ugly.

#include <iostream>
#include <cstdlib>
using namespace std;
class myclass
{
    public:
    void class_function()
    {
        cout << "Class Function Called" << endl;
    }
};
int main()
{
  void(myclass::*myfunction)() = &myclass::class_function; // make function pointer to the class_function
  myclass cls;
  (&cls->*myfunction)(); // when using the function pointer, need to tell the function exactly which instance of the class to call it on
}

In C++, it's not that a class knows about its functions; every instance of a class uses the exact same function code, and when you call a class function the function has a this pointer to tell it exactly which instance of the class it should use the data from. So to make a function pointer to a class function, you need a way to tell the function exactly which instance of the class to work with.

Obviously, if the class function is a static function, it doesn't use any of the class data, so you don't need to identify a particular instance of the class, and it's a bit less ugly.

C++11 std::function makes this a bit more manageable.

Edited 1 Year Ago by Moschops

Thanks so much. For the first time I actually understand this now.

Edited 1 Year Ago by furalise

This question has already been answered. Start a new discussion instead.