0

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().

Community
  • 1
  • 1
algo-geeks
  • 5,280
  • 10
  • 42
  • 54
  • 6
    It's undefined behavior. There is no explanation - anything an happen. – Bo Persson Jul 09 '11 at 18:14
  • 2
    @Bo - well, there *is* an explanation, just not in terms of the C++ standard. More in terms of how C++ is normally compiled. +1 that comment anyway, for undefined behaviour. –  Jul 09 '11 at 18:17

1 Answers1

4

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.

f4.
  • 3,814
  • 1
  • 23
  • 30