Guys plz check the code below:
class Human
{
public:
void chat(Human h)
{
cout << "human";
}
void chat(ComputerScientist c)
{
cout << "computer";
}
};
class ComputerScientist : public Human
{
};
//Main function below
int main()
{
Human* p, p1;
//Uninitialized pointer above;
p->chat(p1); //It shows perfectly the result without ANY error!
}
However, things go tricky if I make a function in derived class ComputerScientist which overrides the Human's one.
class Human
{
public:
virtual void chat(Human* h)
{
cout << "about the weather";
}
virtual void chat(ComputerScientist* c)
{
cout << "about their own computer illiteracy";
}
};
class ComputerScientist : public Human
{
public:
virtual void chat(Human* h)
{
cout << " about computer games";
}
virtual void chat(ComputerScientist* c)
{
cout << " about others’ computer illiteracy";
}
};
And I use the same main function, it appears to be a segmentation fault in the null pointer line. But why?
Things have make change in two places in the second example:
- I used the overriding function by making it virtual.
- The function is taking a pointer as argument.