Beto
Beto

Reputation: 806

function pointer explanation

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;
}

Upvotes: 1

Views: 63

Answers (3)

CyberGuy
CyberGuy

Reputation: 2813

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.

Upvotes: 0

Barry
Barry

Reputation: 302767

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();
}

Upvotes: 2

Darren Griffith
Darren Griffith

Reputation: 79

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

Upvotes: 2

Related Questions