Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Function Pointer as Argument and Classes?

Tags:

c++

Hmm I'm reading some guides on this but I can't figure this out, how do I properly use function pointers in C++?

I have a class that I want to call a function after it has finished whatever it is doing at the moment, like this:

class WindowImages
{
    public:
        void Update()
        {
            for(unsigned int i = 0; i < _images.size(); i++)
            {
                //Do something
                _images[i]->MyFunctionPointer();
            }
        }
        void Add(Image* image, void (*func)(void))
        {
            image->function = func; //this is wrong
            _images.push_back(image);
        }         

    private:
        vector<Image*> _images;
}

class Image
{
    public:
        void ImageClicked();

        void *function(void);
};

void main()
{
    Image* image = new Image();

    WindowImages images;
    images.Add(image, image->ImageClicked);
}

I'm trying to add the image to the vector, and pass a function as argument that will be called when the images class finish doing whatever it has to do with each image. The functions will be different per image but they'll all be in the void function() format.

I've been trying a bunch of things but got nothing so far, how can I do this? Also, if you happen to have a more... beginner friendly tutorial or guide on function pointers (and even maybe C++ 11 lambdas) that'd be really helpful!

like image 944
Danicco Avatar asked Feb 14 '14 21:02

Danicco


1 Answers

You're not using a regular function pointer for your callback. You're using a non-static member function pointer, so the regular function pointer syntax and calling mechanics aren't going to work. There is a significant difference both in the pointer declaration syntax and the mechanism used for invoking non-static members.

To declare a pointer-to-member function for a member of the Image class taking no parameters and returning void, the syntax would be:

void (Image::*function)(). 

Invoking a member function is done using one of two special operators, ->* when using an object pointer, or .* when using an object reference. For example:

// declare a pointer to Image member function
void (Image::*function)();

// assign address of member function
function = &Image::ImageClicked;

// uses ->* for access
Image *pObj = new Image();
(pObj->*function)();

// uses .* for access
Image image;
(image.*function)();

Hope that helps

like image 167
Manpat Avatar answered Sep 19 '22 09:09

Manpat