I want to print out a function pointer using cout, and found it did not work.
But, it worked after I converted the function pointer to void*, so does printf with %p, such as:
#include <iostream>
using namespace std;
int foo() {return 0;}
int main()
{
int (*pf)();
pf = foo;
cout << "cout << pf is " << pf << endl;
cout << "cout << (void *)pf is " << (void *)pf << endl;
printf("printf(\"%%p\", pf) is %p\n", pf);
return 0;
}
I compiled it with g++ and got results like this:
cout << pf is 1
cout << (void *)pf is 0x100000b0c
printf("%p", pf) is 0x100000b0c
So, what does cout do with type int (*)()? I was told that the function pointer is treated as bool, is it true?
And, what does cout do with type void*?
EDIT: Anyhow, we can observe the content of a function pointer by converting it into void* and printing it out using cout. But, it does not work for member function pointers, and the compiler complains about an illegal conversion. I know that member function pointers is rather a complicated structure other than simple pointers, but how can we observe the content of a member function pointer?
There actually is an overload of the << operator that looks something like:
which does what you expect – outputs in hex. There can be no such standard library overload for function pointers, because there are infinite number of types of them. So the pointer gets converted to another type, which in this case seems to be a bool – I can’t offhand remember the rules for this.
Edit: The C++ Standard specifies:
This is the only conversion specified for function pointers.