Why does a virtual function get hidden?
来源:互联网 发布:淘宝打折软件叫什么 编辑:程序博客网 时间:2024/05/01 22:07
Why does a virtual function get hidden?
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.
5 Answers
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.
- Why does a virtual function get hidden?
- Why does a destructor in base class need to be declared virtual?
- Why does this code using `::boost::bind` get a compiler error?
- Why does DOS use 100% CPU under Virtual PC?
- What is a pure virtual function?
- Can a member function template be virtual?
- Why does String.valueOf(null) throw a NullPointerException?
- Erlang: Why does this fail with a 'badarith' exception?
- C# Why does '+' + a short convert to 44
- Why does a declared property use both retain and readonly?
- pure virtual function can has a function body
- Can I call a virtual function from a constructor?
- virtual function
- Virtual function
- virtual function
- virtual function
- Virtual Function
- Why does App restart?
- linux从开机加电到执行main函数之前
- OSGi,Java模块化框架的另类进化
- 验证码客户端验证
- poj 3126
- Confluence 用户属性(User Profile)宏
- Why does a virtual function get hidden?
- unix高级环境编程 例子 代码实现练习 第四章:文件和目录
- 正则表达式30分钟入门教程
- php designer 7註冊碼
- Confluence 用户状态列表(User Status List)宏
- 如何更好地进行性能测试需求分析
- 若初见,若寻常,若是一双人
- 继续前进
- Confluence 查看文件(View File)宏
B
fromA
? – Sven Marnach Nov 10 '10 at 16:17