Calling class method through NULL class pointer in C++

C++ProgrammingServer Side Programming

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;
}
raja
Updated on 26-Jun-2020 13:51:40

Advertisements