Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a function from a function pointer?

How can you call a function from only a pointer to the function. For example, assuming the function has a return type of void:

void print()
{
    std::cout << "Hello World!" << std::endl;;
}

void run_func(void* func)
{
    func(); // what im trying to do (doesnt actually work)
}

int main()
{
    run_func(print);
}

Expected output:

Hello World!

It’s a bit like how std::thread creates a thread from the pointer of a variable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

void print()
{
    std::cout << "Hello World!" << std::endl;;
}

// Change your parameter as follows. You need to wrap function
// pointers in parantheses.
// void run_func(void *func())
void run_func(void (*func)())
{
    func(); // what im trying to do (and now works)
}

int main()
{
    run_func(print);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading