class CBase {
public:
void print()
{
cout<<"In base print func\n";
};
};
class CDerived: public CBase {
public:
void print()
{
cout<<"In derived print func\n";
};
};
int main()
{
CBase b;
CBase* pb;
CDerived d;
CDerived* pd;
pd->print();
return 0;
}
The above code runs fine but when i make the print function in class CBase as virtual it results into segmentation fault.
I think there is some basic logic behind this of which I am not aware. Please give your comments why this is so?
Pointer is not initialized -> undefined behavior.
You need
Also, it doesn’t run fine. Or rather, you’re unlucky that it runs fine. Virtual dispatch requires a virtual table, and since the pointer is not initialized, the virtual table pointer doesn’t exist, that’s why it crashes when the functions is virtual.
When it’s not virtual, it’s still undefined behavior, but it doesn’t crash because it doesn’t use any members.
To prove this, try the following:
it will crash even if the functions is not
virtual.