Null pointer in c++ [duplicate]
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 calling func
with the this
pointer being x
. So in this case it's NULL
From func
you're not using any member variable so you're not using this
.
Anyway, this is bad and as pointed out by Bo Persson, undefined behavior. You should not be doing this.
精彩评论