Possible Duplicate:
Calling class method through NULL class pointer
I was asked this question in the interview can someone answer it?
#include<string>
#include<iostream>
#include <stdio.h>
using namespace std;
class A
{
int k;
public:
void f1()
{
int i;
printf("1");
}
void f2()
{
k = 3;
printf("3");
}
};
class B
{
int i;
public:
virtual void f1()
{
printf("2");
scanf("%d",&i);
}
};
int main()
{
A* a = NULL;
B* b = NULL;
a->f1(); // works why?(non polymorphic)
b->f1(); // fails why?(polymorphic)
a->f2(); //fails why?
}
The last 2 cases are of polymorphic classes. The first case is a normal class .i understand that if i access i in f1 of A it will again give a runtime exception . but i am not getting why that happens
I agree with the other posts that this is undefined behavior, meaning anything can happen when executing the program, including “doing the right thing”.
Now, let’s look at how the calls are implemented:
a->f1()is a normal method call (non virtual). Most compilers will compile this in a similar way as the following code:Meaning the this pointer is actually handled like a parameter to the function (in practice there are frequently some optimizations about how the this pointer is handled, but that is irrelevant here). Now, since f1 doesn’t use the this pointer, the fact that it is null doesnt cause a crash.
a->f2()will actually crash because it uses the this pointer: it updatesthis->k.The call to
b->f1()is a virtual function call, and this is typically implemented using a virtual table lookup asb->vtable[0](). Since b is null, the dereference to read the virtual table crashes.