Possible Duplicate:
What will happen when I call a member function on a NULL object pointer?
Well I think this code and program output explain it self:
#include <iostream>
#include <string>
using namespace std;
class Test
{
public:
void Not_Static(string args)
{
cout << args << endl;
}
};
int main()
{
Test* Not_An_instance = nullptr;
Not_An_instance->Not_Static("Non-static function called with no object?");
cin.ignore();
return 0;
}
program output:
Non-static function called with no object?
why is that possible?
Undefined behaviour. Your program invokes undefined behaviour by invoking a method on a null pointer, so everything is allowed, including your output.
Remember: C++ language's specification don't specify the output of every possible program to leave room for optimizations. Many things are not checked explicitly and can result in behaviour that seems incorrect or illogical, but is simply unspecified.
This behavior is undefined - so it is quite possible it will print that output. The issue is undefined behavior can easily bite you, so you shouldn't do such a thing.
Because it doesn't use this
and therefore doesn't dereference null pointer. Make it virtual and it will likely fail.
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