Why does a virtual function get hidden?
Assuming you intended B
to derive from A
:
f(int)
and f()
are different signatures, hence different functions.
You can override a virtual function with a function that has a compatible signature, which means either an identical signature, or one in which the return type is "more specific" (this is covariance).
Otherwise, your derived class function hides the virtual function, just like any other case where a derived class declares functions with the same name as base class functions. You can put using A::f;
in class B to unhide the name
Alternatively you can call it as (static_cast<A*>(b))->f();
, or as b->A::f();
. The difference is that if B
actually does override f()
, then the former calls the override, whereas the latter calls the function in A
regardless.
Class B does not derive from A so no function F() exists. You probably meant:
class A {
public:
virtual void f() {}
};
class B : public A {
public:
void f(int x) {}
};
Edit: I missed the actual function hiding. See Steve Jessop answer for more thorough explanation.
No, and yes, respectively. If you want the overloading behaviour, you need to say
using A::f;
in B.
B does not derive from A, the correct declaration is:
class B : public A