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