I'm trying to understand how virtual functions work, and I am stuck at a certain part.
I have written this small programm:
class First
{
public:
virtual void f(int a)
{
cout << "First!" << endl;
cout << a << endl;
}
};
class Second : public First
{
public:
void f(int a) {
cout << "Second!" << endl;
cout << a << endl;
}
};
void main() {
Second s;
First *p = &s;
p->f(5);
First n;
p = &n;
p->f(3);
_getch();
}
This code results in:
Second! 5 First! 3
However, if I change int in the Second::f() function to a different type, like this:
class First
{
public:
virtual void f(int a) {
cout << "First!" << endl;
cout << a << endl;
}
};
class Second : public First
{
public:
void f(double a) { //double instead int here!
cout << "Second!" << endl;
cout << a << endl;
}
};
void main() {
Second s;
First *p = &s;
p->f(5);
First n;
p = &n;
p->f(3);
_getch();
}
My program never calls Second::f(), and I'm getting this as a result:
First! 5 First! 3
Can someone explain to me why this happens?
void f(int a)andvoid f(double a)are two distinct function declarationsp->f(5.0);to see the difference.overrideis not required it was introduced to help in exactly such cases. Ifoverridewas used compiler would error thatvoid f(double)doesn't override anything pointing at the problem. I'm surprised both answers (so far) doesn't mention itvoid mainis not legal C++ (it must beint main),using namespace stdis a bad habit and_getch();solves the wrong problem.