0

I want to be able to pass a function from a class called Game inside of a namespace called Application to another function inside a class called Button inside the namespace Engine however I'm unsure how to do it and how to call the function.

Background information, the Game class has an entity that, when clicked I want to call a function that is stored in the Button component.

Game.h

namespace Application
{
    class Game
    {
        void Print(Engine::ButtonData data)
        {
            if (data.buttonPressed == Engine::MouseButton::Left)
                std::cout << "Left\n";
            else if (data.buttonPressed == Engine::MouseButton::Right)
                std::cout << "Right\n";
        }

        e1->button = new Engine::Component::Button(Print); // This is just where the function is passed to the button class for storage
    };
}

Button.h - Only data is to be stored in this class

namespace Engine
{
    namespace Component
    {
        class Button
        {
        public:
            Button() {}
            
            Button(void(* callback)(ButtonData))
                : m_Callback(callback)
            {}

            void(* m_Callback)(ButtonData);
        };
    }
}

Entity Manager - Where the function needs to be called

comp->m_Callback(ButtonData(
                        Mouse::GetCurrentButton(),
                        std::pair<int, int>(Mouse::GetMouseX(), Mouse::GetMouseY()),
                        comp->m_Callback)
                    );

Any help would be great, thanks.

Callum S
  • 213
  • 2
  • 10
  • 1
    Please provide a [mre] demonstrating what you intend to do. – user17732522 Jan 16 '22 at 10:35
  • 1
    I usually use std::functions nowadays because of their flexibility : Some ideas here https://stackoverflow.com/questions/14306497/performance-of-stdfunction-compared-to-raw-function-pointer-and-void-this – Pepijn Kramer Jan 16 '22 at 10:42
  • @user17732522 I've added some code snippets, however I don't see the relevancy as I'm asking how to do something now how to fix something that is broken – Callum S Jan 16 '22 at 10:53
  • @CallumS Without some code it is not clear what exactly you want to do. For example, still, it is not clear to me on what `Game` instance you want the function to be called. Is `e1->button` supposed to be a non-static member of `Game` and is the function supposed to be called on the `Game` object containing that `Button` object? – user17732522 Jan 16 '22 at 11:02
  • Does this answer your question? [Callback functions in C++](https://stackoverflow.com/questions/2298242/callback-functions-in-c) – zkoza Jan 16 '22 at 11:59

0 Answers0