0

I am just curious that how is this program able to print the statement of func() of class.

#include <iostream>
using namespace std;
class foo
{
    public:
        void func ()
        {
            cout << "In func" << endl;
        }
    private:
        int a;
};

int main () {
    foo *f1 = NULL;
    f1->func();
}

Compiler version: g++ (Ubuntu/Linaro 4.4.7-1ubuntu2) 4.4.7 Copyright (C) 2010 Free Software Foundation, Inc.

How is that I am able to get the print of method func()?

2 Answers2

0

Dereferencing a null pointer yields Undefined Behaviour.

I can guess why this still works for you (but again it's UB!), but if you try to access a member variable in func() I'm pretty sure it will stop working.

David Haim
  • 25,446
  • 3
  • 44
  • 78
0

Dereferencing a NULL pointer means that you have undefined behavior.

However in this case on most implementations you will end up in correct function with this being NULL, the normal implementation of calling a non-virtual method is to set the hidden parameter this as being the pointer to the object (in this case NULL) and then just call the function. If you don't access member variables or call virtual methods you should be fine in most implementations.

Since you can't access members or call virtual functions or in any other way do anything useful with this pointer you're pretty close to the scenario of a static method and I'll suggest one use that instead if the this pointer is not used.

For the corner case where you want to be able to do nothing else with the this pointer than check for NULLness you could still use a static method and explicitely pass the pointer to the object:

  static void func(foo* diz) {
       cout << "In func" << endl;

       if( diz != NULL ) {
           diz->actual_work_on_diz();
       }
  }
skyking
  • 13,817
  • 1
  • 35
  • 57