Why can I call a non-statistical member function without an object instance?

Possible duplicate:
What happens when I call a member function on a NULL object pointer?

Well, I think this code and program output explains itself:

#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:

A non-static function called without an object?

Why is this possible?

+6
source share
3 answers

Undefined. Your program invokes undefined behavior by calling a method with a null pointer, so it is allowed , including your output.

Remember: the C ++ language specification does not indicate the output of each possible program to leave room for optimization. Many things are not explicitly tested and can lead to behavior that seems wrong or illogical, but just vague.

+9
source

This behavior is undefined - so it is entirely possible that it will print this output. The problem is that undefined behavior can bite you, so you should not do this.

+5
source

Because it does not use this and therefore does not look for a null pointer. Make it virtual, and it most likely will fail.

+2
source

Source: https://habr.com/ru/post/906695/


All Articles