What is the boolean value that is returned when a fucntion call is made on a null object in C++?
ClassDummy* dummy = NULL;
if (!dummy->dummy_function(1,2,3)) {
// Do Something
}
Shouldn't this return an error according to C++11 standards?
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.
Trying to dereference a null pointer like this will result in undefined behavior.
(Typically, a core dump or memory access exception on most systems.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With