This is likely but not guaranteed to not cause an error because your B_method is effectively static
.
- The method can be looked up and called into without dereferencing the class pointer
- The method itself doesn't need to dereference the class pointer.
As soon as the method becomes virtual
(and now requires the class pointer for access to the vtable to look up the function address), accesses class data, or you sneeze or look at the compiler funny, you will be dealing unbound memory access.
And I should stress that while dereferencing the class pointer is not required by a hypothetical compiler, it is allowed, and could be required by any particular compiler implementation.
Further reading...check out the accepted answer Difference between Object and instance : C++ Your class pointer is unlikely to be looked at until you access instance data
associated with a particular instance of the class.
Or...another way to put all this. If you can tack on static
in front of your function declaration, calling it with an invalid pointer might work.
See also:
class MyClass
{
public:
int doSomething(int x)
{
printf("%d", x);
return x;
}
};
int main()
{
MyClass *pMyClass = nullptr;
pMyClass->doSomething(42);
}