您的位置:首页 > 其它

Why does a virtual function get hidden?

2014-03-08 08:17 274 查看


Why
does a virtual function get hidden?




up
vote13down
votefavorite

1

I have the following classes:
class A {
public:
virtual void f() {}
};

class B : public A{
public:
void f(int x) {}
};


If I say
B *b = new B();
b->f();


the compiler says error C2660: 'B::f' : function does not take 0 arguments. Shouldn't the function in B overload it, since it is a virtual function? Do virtual functions get hidden like this?

EDIT: I indeed meant to inherit B from A, which shows the same behaviour.

c++ virtual hide
share|improve
this question
edited Nov
11 '10 at 7:05

asked Nov 10 '10 at 16:14





Oszkar

17029

9
Maybe you would like to derive
B
from
A
? – Sven
Marnach Nov
10 '10 at 16:17
add
comment


5 Answers

activeoldestvotes

up
vote27down
voteaccepted
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.

share|improve
this answer
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: