Possible Duplicate:
Accessing class members on a NULL pointer
#include<iostream.h>
class X{
private:
int x;
public:
X() {}
void func() {
cout<<"In func()"<<endl;
}
};
int main(void)
{
X *x=NULL;
x->func();
return 0;
}
I am really surprised with the o/p ,can anyone please explain me how x can access func().
x->func()just means you’re callingfuncwith thethispointer beingx. So in this case it’sNULLFrom
funcyou’re not using any member variable so you’re not usingthis.Anyway, this is bad and as pointed out by Bo Persson, undefined behavior. You should not be doing this.