I am curious as to what part of the dereferencing a NULL ptr causes undesired behavior. Example:
// #1
someObj * a;
a = NULL;
(*a).somefunc(); // crash, dere
The second example is also undefined behavior, yes. You are only allowed to call member functions on a valid object. And a null pointer does not point to a valid object.
The reason why it appears to work is that member functions are typically implemented roughly like this:
void anotherfunc(anotherObj* this, someObj& arg);
That is, the "this" pointer is basically passed to the function as a separate argument. So while calling the function, the compiler doesn't check that the this
pointer is valid, it just passes it to the function.
It is still undefined behavior though. The compiler isn't guaranteed to let this work.