I know that it is UB. I was just curious how that function is executed
thru a NULL pointer.
It seems that this function is as good as a non-member function
executing at its own and do not require any valid pointer.
but whenever we add a data member it simply crashes.
Back to my curiosity question of what platform and compiler is this?
Just so we (clc++) can use it as an example of where this specific
instance of UB crashes the program.
I just wanted to know what causes that crash and why it is necessary to
add a data member to re-produce that crash.
Not to sound snarky, but why do you care? Since attempting to call a
method through a NULL pointer invokes Undefined Behviour, regardless of
whatever the content of your class is, why does it matter when it
crashes? (I explained why _I_ want to know when this crashes....)
However, the nutshell version (and definitely implementation-specific)
is that in most cases the compiler converts function calls of the form:
obj->method(param1, param2);
into something resembling:
method(obj, param1, param2);
Inside method(), the first parameter(obj) gets assigned to the "this"
pointer, and the rest of the parameters are dealt with as normal.
However, simply adding a member variable "shouldn't" cause anything to
blow up unless you attempt to access that variable within the method.
Up to that point you haven't (necessarily) caused the program to attempt
to dereference the NULL pointer. If you tried to access the member
variable:
a = 4;
That would be "converted" to:
this->a = 4;
This would have to dereference the NULL pointer, and attempt to assign 4
into whatever appropriate memory location relative to NULL that a
happens to lie on (and is likely not writable memory...).
And more things start coming into play if method() happens to be virtual....
Again, all of this is conjecture, and compiler implementors can
implement all of this in whatever way they choose. It all boils down
to: Calling methods through a NULL pointer is Undefined Behaviour.