Calling a member function on a NULL object pointer in C++

C++ProgrammingServer Side Programming

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. The actual results depend on the compiler used.

A program that demonstrates this is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class Demo {
   public :
   void fun() {
      cout << "This member function is called through Null object pointer.";
   }
};
int main() {
   Demo *ptr = NULL;
   ptr->fun();
   return 0;
}

Output

The output of the above program is as follows.

This member function is called through Null object pointer.

Now, let us understand the above program.

The class Demo contains a member function fun(). This function displays "This member function is called through Null object pointer." The code snippet for this is given as follows.

class Demo {
   public :
   void fun() {
      cout << "This member function is called through Null object pointer.";
   }
};

In the function main(), the object null pointer ptr is created. Then the member function fun() is called using ptr. The code snippet for this is given as follows.

int main() {
   Demo *ptr = NULL;
   ptr->fun();
   return 0;
}
raja
Published on 21-Nov-2018 12:32:40
Advertisements