0

I have a request for function pointer by C++. below is the sample what I need:

in API file:

class MyClass {
    public:
        void function1();
        void function2();
        void function3();
        void function4();
};

in main file:

MyClass globalglass;

void global_function_call(???)// <---- how to do declaration of argument???
{
    //Do *function
}

int main()
{
    global_function_call(&globalglass.function1()); // <----  pseudocode, I need to use global class 
    global_function_call(&globalglass.function2());
    global_function_call(&globalglass.function3());
    global_function_call(&globalglass.function4());

    return 1;   
}

I have no idea to do declaration...

3
  • What is global_function_call expected to do? Should it call functionX on globalglass specifically or do you want to pass the object on to it as well? Commented Jan 10, 2022 at 3:47
  • Only having a function pointer to a member &MyClass::function1 is not enough to be able to call it, you also need to provide a class instance to call. Have a look at : learncpp.com/cpp-tutorial/…. I find that syntax the most useful/reusable : auto lambda1 = [&globalclass]{global_class.function1();}; global_function_call(lambda1); Commented Jan 10, 2022 at 3:48
  • Oh and do try to come up with a design where you will not need a global instance. It is not good design for maintainability/testability. You might want to learn about dependency injection : en.wikipedia.org/wiki/Dependency_injection_ Commented Jan 10, 2022 at 3:53

1 Answer 1

2

To do what you are asking for, you can use a pointer-to-member-method, eg:

MyClass globalglass;

void global_function_call(void (MyClass::*method)())
{
    (globalglass.*method)();
}

int main()
{
    global_function_call(&MyClass::function1); 
    global_function_call(&MyClass::function2);
    global_function_call(&MyClass::function3);
    global_function_call(&MyClass::function4);

    return 1;   
}

Online Demo

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.