Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling class method through NULL class pointer [duplicate]

Tags:

c++

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?

like image 593
Adil Avatar asked Mar 24 '10 04:03

Adil


People also ask

What happens if you call a null function pointer?

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.

Can you call a function from a Nullptr?

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.

Can you set a pointer to null?

We can directly assign the pointer variable to 0 to make it null pointer.

Does null pointer return false?

A pointer will convert to Boolean false if it is a null pointer, and true otherwise.


1 Answers

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.

like image 75
James McNellis Avatar answered Sep 22 '22 10:09

James McNellis