Adil Adil - 3 months ago 11
C++ Question

Calling class method through NULL class pointer

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?

Answer

(I can't recall where I've got this knowledge, so I could be completely wrong)

Under the hood most compilers will transform your class to somthing 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 transform to:

_abc_print( NULL)

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. And here is why:

  1. Because standard states it yields undefined behavior (could anyone give a link or at least reference(chapter N, par M...)?)
  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
Comments