For example:
using namespace std;
#include <iostream>
void funcOne() {
}
void funcTwo( int x ) {
}
int main() {
void (*ptrOne)() = funcOne;
cout << ptrOne << endl; //prints 1
void (*ptrTwo)( int x ) = funcTwo;
cout << ptrTwo << endl; //prints 1
int (*ptrMain)() = main;
cout << ptrMain << endl; //prints 1
}
Does anyone know the reasoning behind this? At first I thought it was because the functions don't exist in memory since I never call on them, and thus they never get added to the stack. But even the value of a pointer to the main function prints out 1.
Try this instead:
I think normally, function overloading rules mean that the version of
<<
being called isoperator<<(bool)
, which means:Gets transformed into:
Which is the same as:
Function pointers do not implicitly convert to
void *
, which is whatoperator <<
overloads on.This is specified by omission in C++11 §4.10/2:
Function types are not object types.
Moreover, you can't even do it using
static_cast
. Functions and objects may live in completely different address spaces (this is called Harvard architecture), with differently-sized pointers. Converting a function pointer tovoid *
can maybe be done withreinterpret_cast
: it's "conditionally-supported" (C++11 §5.2.10/8). Such avoid *
should only be used for printing or conversion back to the original function pointer type.Use it like this, or it will be converted to a
bool
type.Operator overloading in C++ adds all sorts of nasty complexities. (It lets you do awesome stuff too—but sometimes it's just a headache.)
As explained in the other answers, C++ is doing some automatic type coercion on your function pointers. If you just use the good ol' C-style
printf
you should get the results you're expecting: