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 declarations – Swaneyp->f(5.0);
to see the difference. – Postmistressvoid f(int a)
should bevirtual void f(int a) override
in theSecond
class if you want to override it... – Lytleoverride
is not required (and didn't exist before C++11) – SwaneyFirst
. – Offenp->f(5.0);
. That demonstrates that the int version is not affected by a float version in Second. Only the float version in First is overridden. – Postmistressoverride
is not required it was introduced to help in exactly such cases. Ifoverride
was 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 it – Balvoid main
is not legal C++ (it must beint main
),using namespace std
is a bad habit and_getch();
solves the wrong problem. – Offen