Why does calling method through null pointer "work" in C++? [duplicate]

Possible Duplicate:
Calling class method through NULL class pointer

#include <iostream>
using namespace std;
class test
{
    int i;
public:
    test():i(0){ cout << "ctor called" << endl;}
    void show()
    {
        cout<<"show fun called"<<endl;
    }
};

int main(int argc , char *argv[])
{
    test *ptr = NULL;
    ptr->show();
    return 0;
}

clearly, no ctor will be called. Is this standard? or just some compiler optimization as this pointer is not used in show() member function?


The pointer isn't needed to call the method. The type of the pointer is known, so the code for the method is known. The method doesn't use this, so it runs the code just fine. It's undefined behavior, but its more efficient not to check if the pointer is NULL, so it runs.


If you look at the assembly (for at least one compiler), you can see why it runs (even though it is undefined behavior as many have pointed out). For these two lines:

test *ptr = NULL;
ptr->show();

This assembly is generated (in one compiler I just tried):

00000004: C7 45 FC 00 00 00  mov         dword ptr [ebp-4],0
          00
0000000B: 8B 4D FC           mov         ecx,dword ptr [ebp-4]
0000000E: E8 00 00 00 00     call        ?show@test@@QAEXXZ

It pushes the NULL (0) on the stack and calls the method since the address of the method is independent of the actual object instance.