Function pointer vs Function reference

John picture John · Oct 5, 2013 · Viewed 9.1k times · Source

In the code below, function-pointer and what i considered as "function-reference" seems to have identical semantics:

#include <iostream>
using std::cout;

void func(int a) {
    cout << "Hello" << a << '\n';
}
void func2(int a) {
    cout << "Hi" << a << '\n';
}

int main() {
    void (& f_ref)(int) = func;
    void (* f_ptr)(int) = func;

    // what i expected to be, and is, correct:
    f_ref(1);
    (*f_ptr)(2);

    // what i expected to be, and is not, wrong:
    (*f_ref)(4); // i even added more stars here like (****f_ref)(4)
    f_ptr(3);    // everything just works!

    // all 4 statements above works just fine

    // the only difference i found, as one would expect:
//  f_ref = func2; // ERROR: read-only reference
    f_ptr = func2; // works fine!
    f_ptr(5);

    return 0;
}

I used gcc version 4.7.2 in Fedora/Linux

UPDATE

My questions are:

  1. Why function pointer does not require dereferencing?
  2. Why dereferencing a function reference doesn't result in an error?
  3. Is(Are) there any situation(s) where I must use one over the other?
  4. Why f_ptr = &func; works? Since func should be decayed into a pointer?
    While f_ptr = &&func; doesn't work (implicit conversion from void *)

Answer

Kerrek SB picture Kerrek SB · Oct 5, 2013

Functions and function references (i.e. id-expressions of those types) decay into function pointers almost immediately, so the expressions func and f_ref actually become function pointers in your case. You can also call (***func)(5) and (******f_ref)(6) if you like.

It may be preferable to use function references in cases where you want the &-operator to work as though it had been applied to the function itself, e.g. &func is the same as &f_ref, but &f_ptr is something else.