Calling class method through NULL class pointer [duplicate]

I have following code snippet:

class ABC{
public:
        int a;
        void print(){cout<<"hello"<<endl;}
};

int main(){
        ABC *ptr = NULL:
        ptr->print();
        return 0;
}

It runs successfully. Can someone explain it?


Calling member functions using a pointer that does not point to a valid object results in undefined behavior. Anything could happen. It could run; it could crash.

In this case, it appears to work because the this pointer, which does not point to a valid object, is not used in print.


Under the hood most compilers will transform your class to something like this:

struct _ABC_data{  
    int a ;  
};  
// table of member functions 
void _ABC_print( _ABC_data* this );  

where _ABC_data is a C-style struct and your call ptr->print(); will be transformed to:

_ABC_print(nullptr)

which is alright while execution since you do not use this arg.


UPDATE: (Thanks to Windows programmer for right comment)
Such code is alright only for CPU which executes it.
There is absolutely positively no sane reason to exploit this implementation feature. Because:

  1. Standard states it yields undefined behavior
  2. If you actually need ability to call member function without instance, using static keyword gives you that with all the portability and compile-time checks

Most answers said that undefined behaviour can include "appearing" to work, and they are right.

Alexander Malakhov's answer gave implementation details which are kind of common and explain why your situation appeared to work, but he made a slight misstatement. He wrote "which is alright while execution since you do not use this arg" but meant "which appeared to be alright while execution since you do not use this arg".

But be warned, your code still is undefined behaviour. It printed what you wanted AND it transfered the balance of your bank account to mine. I thank you.

(SO style says this should be a comment but it's too long. I made it CW though.)