1

I am learning C++ and just playing around with function pointers.

I have this very simple program, but I do not get any output when called. Would you mind explaining why? I think it's because inside the printTheNumbers, I never called the function itself I just make a reference to it?

void sayHello()
{
    cout << "hello there, I was accessed through another function\n";
}

void accessFunctionThroughPointer(int a, int b, void(*function)())
{

}

int main(int argc, const char * argv[])
{
    printTheNumbers(2, 3, sayHello);

    return 0;
}
3
  • 1
    Add this line to printTheNumbers(): function(); Commented Apr 17, 2015 at 21:21
  • no offense, but as you said you are still learning c++ (and posting beginner code that has nothing to do with the solution - addTheNumbers) it would be better for learning to play around with what you know (functions, etc) and learn dealing with strings, reading from commandline, parsing arguments and so on. IMHO function pointers are nice but more complicated and not often needed... Commented Apr 17, 2015 at 21:34
  • edited. I need to study this for a final not functions. Thanks i guess? @relascope Commented Apr 17, 2015 at 21:51

3 Answers 3

2

Your function isn't doing anything:

void printTheNumbers(int a, int b, void (*function)()){
    // there is no body here    
}

You need to actually call the passed-in function pointer:

void printTheNumbers(int a, int b, void (*function)()){
    function();
}
Sign up to request clarification or add additional context in comments.

1 Comment

how about if I make the sayHello() to return a string instead of void.
2

You pass in the sayHello function to printTheNumbers, but you never call the passed in function.

Comments

0

You need to call the function manually. Prove:

Code snippet

More over consider to use std::function. Example:

#include <functional>

void printTheNumbers(int a, int b, std::function<void()> function){ 
    function();
}

In most cases std::function is enough and more readable.

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.