Null pointer access in C++

Language implementation quirks can lead to interesting things. Lets say I have the following C++ code.

 class MyClass{    int i;public:    void foo()    {        cout << "Hello" << endl;        //i = 5;    }}; int main(int argc, char* argv[]){    MyClass *mc; mc->foo();     return 0;}

What is the outcome of this piece of code? Since we haven't allocated mc and accessing foo via an unassigned pointer most people expect a crash. However on most compilers this is garaunteed to print "Hello" with out any crash.

What is important to note here is that since foo is not a virtual method the lookup doesn't go through the vtable and hence mc->foo() call is compiled here as MyClass::foo(null)through appropriate mangled name). As long as foo doesn't access any of the instance member of MyClass the null this pointer remains unused. If the commented line is foo is uncommented we get a crash.

If the foo method is made virtual then lookup goes thrugh the vtable and the application crashes.