in the below program for both class pointers pointing to null. Class contains normal function executing but class contains virtual function getting segmentation fault.
#include <cstdio>
using namespace std;
class A
{
public:
void Function()
{
printf("class A Function execute test!\n");
}
};
class B
{
public:
virtual void Function(){
printf("class B Function execute test!\n");
}
};
int main()
{
A *pA=NULL;
pA->Function();
B *pB=NULL;
pB->Function();
return 0;
}
A *pA=NULL; // this means it actually points to the address 0x0
Yes there is no object of class A.
But since A has no fields in it anyway (and if it were to only if you access them it would matter) there is nothing you access there anyway.
Your Function lies somewhere in the code segment and to execute it your compiler doesn't care if there is actually an object of A at 0x0. He has all the information he needs.
1 2
B *pB=NULL;
pB->Function();
Well it's a virtual function thus your compiler is not creating a function called "Function" (there is none in the code segment).
Well trying to call something that doesn't exist is going to fail obviously