This is the same old story of NULL
(or invalid) object pointers; for the standard, calling a method on a NULL
object pointer results in undefined behavior, which means that, as far as the standard is concerned, it could work perfectly fine, it could blow up the computer or kill some random people.
What happens here is a consequence of the typical implementation of classes by C++ compilers: classes usually are actually structures that contain just the fields, and all the methods are actually functions which take as a hidden parameter the this
pointer.
Now, in this kind of implementation if you call a method with a NULL
this
pointer, if it doesn't access any of the fields it won't actually dereference this
, so it should run fine (as happens with func1
).
If, instead, the method tries to access any of the fields (e.g. func2
), it will dereference the this
pointer, which, being NULL
, will lead to a crash (dereferencing a NULL
pointer it's, again, undefined behavior, but usually it results in a crash).
Note that if the methods that you're calling are virtual it's almost sure that calling them with a NULL
this
pointer will lead to a crash, since the virtual calls are resolved via the vtable (a function pointer array), which is hidden at the beginning of the class.
By the way, void main()
is not standard; it should be int main()
(argv
and argc
are, instead, optional).