1

I have a struct Game with a function pointer called onBegin

struct Game {
  // ...
  void (*onBegin)(Game&);
  // ...
};

What I am attempting to do is allow the user to create their own onBegin function, in which they could say

void CustomFunc(Game& g) {
  // Do something
}

Game g = Game();
g.onBegin = *CustomFunc;

What I am attempting to do is make a function and then set the pointer onBegin to point at that default function.

struct Game {
public:
  void (*onBegin)(Game&);
private:
  void defualtOnBegin(Game&);
};

// In the constructor
Game::Game() {
  // ...
  this->onBegin = this->defaultOnBegin; // This is what is giving me the error
}

I receive the error: a pointer to a bound function may only be used to call the function and do not know what is wrong here.

3
  • 2
    it's a member function pointer, differs from free functions. Commented May 12, 2022 at 5:23
  • 1
    so if i wanted to achieve what im getting at, i couldnt make the default function apart of the game struct? Commented May 12, 2022 at 5:50
  • 1
    Or make it static. It gets the instance by its parameter anyway. Commented May 12, 2022 at 5:55

1 Answer 1

1

What I am attempting to do is allow the user to create their own onBegin function...

You could achieve that in different ways, however as you want to go for a function-pointer approach, you might want to utilize std::function like:

#include <iostream>
#include <functional>

struct Game {
    public:
        Game(std::function<void(Game&)> customOnBeginFnc = nullptr) {
            if(customOnBeginFnc) {
                customOnBeginFnc(*this);
            } else {
                defaultOnBegin(*this);
            }
        }

    private:
        void defaultOnBegin(Game&) {
            std::cout << "Default 'onBegin'\n";
        }
};

void customOnBegin(Game&) {
    std::cout << "Custom 'onBegin'\n";
}

int main() {

    {
        std::cout << "Starting a 'default' game...\n";
        Game g;
    }

    {
        std::cout << "Starting a 'customized' game...\n";
        Game g(customOnBegin);
    }
}

Run it here.

The advantage of that approach would be that you are not limited to free functions but you could also bind a member function to it via a lambda or std::bind.

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

1 Comment

although std::function is a valid approach, the code you present doesn't benefit from it.

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.