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?
Initializing a pointer to a function, or a pointer in general to NULL helps some developers to make sure their pointer is uninitialized and not equal to a random value, thereby preventing them of dereferencing it by accident.
Calling a member function on a NULL object pointer in C++A class member function can be called using a NULL object pointer. Note − This is undefined behaviour and there is no guarantee about the execution of the program.
We can directly assign the pointer variable to 0 to make it null pointer.
A pointer will convert to Boolean false if it is a null pointer, and true otherwise.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With