16

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?

1
  • Note: You can't pass functions. You can only pass references or pointers to functions. Commented Aug 22, 2011 at 12:08

1 Answer 1

35
#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 );
}
Sign up to request clarification or add additional context in comments.

4 Comments

Just out of curiosity, why would I want to use a reference to a function instead of a pointer to a function?
@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.
@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.
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.

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.