0

I am having trouble compiling the following code. I am usually OK with using callback functions, but it seems that when using a member function, it has issues. Do you know what is the problem with my declaration/definition of the parameter startPlayback?

class VmapPlayer
{
        void startPlayback();
        void playAdBreak(int a, void (*callback)());
};

void VmapPlayer::playAdBreak(int a, void (*callback)())
{
    cout << a << endl;
    //callback();
}

void VmapPlayer::startPlayback()
{
    playAdBreak(5, startPlayback);     // Compile issue with "startPlayback" parameter
}

1 Answer 1

1

void (*callback)() declares callback as a function pointer, but startPlayback is not a free function, but a member function. This is one way to fix it:

class VmapPlayer
{
    void startPlayback();
    void playAdBreak(int a, void (VmapPlayer::*callback)());
};

void VmapPlayer::playAdBreak(int a, void (VmapPlayer::*callback)())
{
    cout << a << endl;
    (this->*callback)();
}

void VmapPlayer::startPlayback()
{
    playAdBreak(5, &VmapPlayer::startPlayback);
}

If you need more flexibility, and C++11 is available, you could use std::function<void()> to hold your callback, and fill it with a lambda expression, like [this](){ startPlayback(); }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.