In the following code:
Please tell me why only derived class member function is called, is it because of hiding? And why an error doesn't occur in b.func(1.1);, the parameter is int x.
#include <bits/stdc++.h>
using namespace std;
class A {
public:
virtual int func(float x)
{
cout << "A";
}
};
class B : public A {
public:
virtual int func(int x)
{
cout << "B";
}
};
int main()
{
B b;
b.func(1); // B
b.func(1.1); // B
return 0;
}
Yes it's because of hiding. This is one of the main reasons you should always add the special identifier
overrideon functions you intend to override:This will cause the compiler to complain about not actually overriding.
And floating point values can be implicitly converted to integers.