Calling class method through NULL class pointer in C++


A class method can be can be called using a NULL class pointer.

Note − This is undefined behaviour and there is not 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 Example {
   public :
   void func() {
      cout << "The function is called through Null class pointer.";
   }
};
int main() {
   Example *p = NULL;
   p->func();
   return 0;
}

Output

The output of the above program is as follows.

The function is called through Null class pointer.

Now, let us understand the above program.

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

class Example {
   public :
   void func() {
      cout << "The function is called through Null class pointer.";
   }
};

In the function main(), the class null pointer p is created. Then func() is called using p. The code snippet for this is given as follows.

int main() {
   Example *p = NULL;
   p->func();
   return 0;
}

Updated on: 26-Jun-2020

328 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements