Access to the function through a pointer after setting the pointer to zero

I do not understand how the code below gives the given result.

#include <iostream>
using namespace std;

class MyClass
{
   public: 
   void doSomething()
   { 
       cout<<"Inside doSomething"<<endl;  
   }
};

int main()
{   
    MyClass obj;
    MyClass *ptr=&obj;
    ptr->doSomething();
    ptr=NULL;
    ptr->doSomething();
}

Output


Inside doSomething
Inside doSomething

I executed a function with a null pointer, and it actually calls the function. Getting the address stored in ptr using cout ptr shows that ptr is set to 0 after the ptr = NULL statement; But it still calls doSomething (). What is really going on inside?

+4
source share
2 answers

This is Undefined Behavior , and absolutely anything can happen, including work. This is not reliable!

, , MyClass::doSomething() this ( NULL, ).

MyClass doSomething(), crash (segfault):

class MyClass
{
   int someNum;
   public: 
   void doSomething()
   { 
       cout<< "Inside doSomething: " << this->someNum <<endl;  
   }
};

( gcc 4.9.2 Linux segfault.)


, , using namespace std; endl.

+9

, , .

- , , , .

, , . , .

, :

doSomething(MyClass * this)
{
  // Will work OK if 'this' pointer is NULL, but NOT used.

  // Will Crash if 'this' pointer is used.
  this->data = 100;
}
+2

All Articles