And to answer all your future "shouldn't C++ tell me I'm doing something wrong" questions in advance: no. C++ optimizes heavily for the case where your program works, at the expense of saying almost nothing about the case where you have a bug.
–
user2357112Jun 8 '14 at 8:44

5 Answers
5

Unless dummy has been declared at namespace scope, it is uninitialized and its value is unspecified, i.e. it may or may not be null. Invoking a member function on a nullptr, or on a pointer that is pointing to invalid memory, is undefined behavior.

You might get away with the correct result if the member function you invoke doesn't access any other data members of the class; in other words, if it doesn't dereference the this pointer. However, regardless of whether you obtain the expected result or not, it is still undefined behavior.

Compilers are not required to detect such invalid function calls. If you do something obvious, like initialize an object pointer to nullptr and then invoke a member function on it, you may see a diagnostic from the compiler, but this is not guaranteed.

In the original question dummy had an unspecified value, maybe null. The effect after the edit isn't changed, though: The behavior is undefined. Its not an error any tool is required to detect: it is the mandate of the programmer to call member functions only on valid objects.

Calling a method through a null pointer has undefined behavior. The code is invalid, but the compiler is not required to tell you that it is.

The C++ standard defines many cases where, even though the code is invalid, the compiler is not required to give a "diagnostic". In many cases, the reason is just because it is very difficult for the compiler to determine whether or not the code is valid. In your particular code, this is pretty easy, and some compilers may in fact give a warning about it if you use the proper warning level. However, it wouldn't be too difficult to construct a more complicated example where the compiler wouldn't easily be able to tell whether the pointer was null or not. Standardizing exactly how complex the code has to be before the compiler doesn't need to give a diagnostic would be difficult, and probably pointless, so it is just left up to each implementation to make that decision.