According to C++ Standard, it’s perfectly acceptable to do this:
class P
{
void Method() {}
};
...
P* p = NULL;
p->Method();
However, a slight change to this:
class P
{
virtual void Method() {}
};
...
P* p = NULL;
p->Method();
produces an access violation when compiled with Visual Studio 2005.
As far as I understand, this is caused by some quirk in Microsoft’s compiler implementation and not by my sheer incompetence for a change, so the questions are:
1) Does this behavior persist in more recent versions of VS?
2) Are there any, I don’t know, compiler settings that prevent this access violation?
According to C++ Standard, it’s perfectly acceptable to do this
No it is not!
Dereferencing a
NULLpointer is Undefined Behavior as per the C++ Standard.[#1]However, If you do not access any members inside a non virtual member function it will most likely work on every implementation because for a non virtual member function the
thisonly needs to be derefernced for accessing members ofthissince there are no members being accessed inside the function hence the result.However, just because the observable behavior is okay does not mean the program is
well-formed.correct.It still is ill-formed.It is an invalid program nevertheless.
The second version crashes because while accessing a virtual member function, the
thispointer needs to be dereferenced just even for calling the appropriate member function even if there are no members accessed within that member function.A good read:
What’s the difference between how virtual and non-virtual member functions are called?
[#1]Reference:
C++03 Standard: §1.9/4