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. 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;
}
Updated on: 2020-06-26T13:47:22+05:30

979 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements