Consider following piece of code:

using namespace std;

class A
void func ()
cout << "akash";
int i;

main ()
A *obj = NULL;
obj->func ();

Will it produce a segmentation fault because of NULL pointer dereference? The answer is - NO.

The reason is that call to member functions is expanded like below:

func(class a * this)

As long as we do not access 'this', there will not be any problem. So Null pointer dereference problem will not happen in this case.

But careful, if we define this function as virtual or access any data member inside this function, it will produce a core. The thumb rule is that any NULL dereference, where you are not accessing 'this', will work.

A class method is similar as a global method (so, there is only one function address even if there are multiple instances of the class or even no instance at all). When the method is called, the address of the instance ('this' pointer), on which the function is called, is passed to the function. This means that as long as you don't access any variables of the class, you can perfectly call the function even if the instance is NULL.

But please, don't make this kind of programming as practice. Because you never know what will happen in future with functions, which are working properly currently. I caught this while debugging something and am not planning to use this trick for coding.

Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.