2

Possible Duplicate:
Accessing class members on a NULL pointer

A very silly question or may be my conceptual doubt.

    #include <iostream>

    using namespace std;

    class A
    {
            public:
            void print()
            {
                    cout<<"Printing\n";
            }
    };

    int main()
    {
            A * a = NULL;
            a->print();
            return 0;
    }

The output is: Printing

How is a pointer(which is NULL) able to access member function of class A.

Please explain... may be its just a silly question but I had the impression that a NULL pointer will not access the class's member function.

Community
  • 1
  • 1
Kundan Kumar
  • 1,974
  • 7
  • 32
  • 54

3 Answers3

7

Dereferencing a NULL pointer, as you do in your code, is undefined behavior. One of the possibilities of such undefinedness is that it may just work. But it may crash the next time, or do something totally unexpected.

Since you are not using the implicit this argument in your member function print, seems like such NULL pointer never needs to actually be dereferenced.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
5

Dereferencing NULL results in undefined behaviour (UB). UB does not mean "must crash" or "must do something weird".

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
3

As stated, yes this is undefined behaviour, but the reason why it works is...

It's a null pointer but still of the defined type "A", each time you create an instance of the class it does not duplicate the methods, it just allocates ram and calls the constructor method with the newly allocated address.

Calling the method will still work, provided your method does not use any class internals, which your's does not, however if you do desire such functionality you should obviously use a static method instead where the compiler will complain bitterly if you try to access 'this' or any of the class internal members.

If you break inside the method and inspect the value of 'this' you will find that it is NULL.

Geoffrey
  • 10,843
  • 3
  • 33
  • 46