14

I have been reading about function pointers and about using them as parameters for other functions.

My question is how would you pass a function by reference without using pointers? I have been trying to find the answer on the Internet but I haven't found a good answer.

I know that you can pass variables by reference like this: void funct(int& anInt);. How would you do something similar to this, but instead of a reference to a variable, a reference to a function was the parameter?

Also, how would you use a reference to the function in a function body?

Hudson Worden
  • 2,263
  • 8
  • 30
  • 45

1 Answers1

33
#include <iostream>
using namespace std;

void doCall( void (&f)(int) )
{
    f( 42 );
}

void foo( int x )
{
    cout << "The answer might be " << x << "." << endl;
}

int main()
{
    doCall( foo );
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • 1
    Just out of curiosity, why would I want to use a reference to a function instead of a pointer to a function? – fredoverflow Aug 22 '11 at 08:07
  • 15
    @FredOverflow: Because a pointer can be null or invalid. A reference guarantees that it's valid and not null (there is no null-reference), or else that there is an error in the program. – Cheers and hth. - Alf Aug 22 '11 at 08:13
  • 4
    @Alf P. Steinbach: "or else that there is an error in the program" That sounds great in theory but if you have something like `sometype &ref = *ptr;` the address in the pointer will be simply copied into the address in the reference, which may be non-valid or null. You might say that the statement above is undefined behavior when `ptr` is non-valid or null, but there won't be any indication of this at compile- or run-time, so it is still up to the programmer to make sure it is valid and non-null, same as if you used a pointer. So I say there isn't any difference to the programmer. – newacct Aug 22 '11 at 21:54
  • 8
    I think there is a great difference. If you build up you whole codebase with using references in every API where null is not a sensible value, then the `sometype &ref = *ptr;` situation won't come up that often because you will have references everywhere. Also there is a semantical difference between accepting a reference and a pointer in an API. Accepting a reference clearly states that the function can't be called with null. If it is a reference, then it's the caller's responsibility, if it's a pointer, then it's the callee's. – Mark Vincze Aug 14 '14 at 07:54