Thursday, December 29, 2011

Calling Member function using NULL pointer

To my surprise, my program did not crash when I called display() by NULL pointer, but it crashed when I tried to access member variable.

#include


#include

using namespace std;

class Test

{

public:

    int p;

   void display() {

       cout << "Test::display()" << endl;

   };

};



int main()

{

    try {

       Test *t = NULL;

       t->display();

       t->p = 5;

    } catch (exception &e) {

      cout << "Dereferencing pointer: " << e.what();

   } catch (...) {

      cout << "Unknown Exception";

   }

   return 0;

}