What is the default value of a function pointer in C++? (Apparently it can't be NULL
, so what is it?)
How is this program supposed to behave and why?
struct S { void (*f)(); };
int main()
{
S s = S();
s.f(); // What is the value of s.f?
}
A function pointer can be NULL and you may assign NULL to it. Have a look here for instance:
I believe the way you call the constructor of the structure(with
()
), f will be NULL.In C++ (and C), pointers (regardless of type) do not have a default value per se; they take what ever happens to be in memory at the time. However, they do have a default initialised value of
NULL
.Default Initialisation
When you don't explicitly define a constructor, C++ will call the default initialiser on each member variable, which will initialise pointers to
0
. However, if you define a constructor, but do not set the value for a pointer, it does not have a default value. The behaviour is the same for integers, floats and doubles.Aside
In your case the object
s
is zero-initialized which means the function pointer isNULL
.Output:
Online demo.
First any pointer can be null. It is the one universal truth about pointers. That said, yours will be null, but not necessarily for the reasons you may think;
This is important because your declaration includes this :
By the definition of value initialization:
Which brings us to what it means for your object-type to be zero-initialized:
The latter is the reason you're pointer is null. It will not be guaranteed-so by the standard given the same code, but changing the declaration of
s
to this:Given a declaration like the above, a different path is taken through the standard:
Which then begs the last question, what is default initialization:
Function pointer can be NULL, this way you can indicate that they don't point to anything!