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.