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
| ||||
comment |
5 Answers
activeoldestvotesup vote27down voteaccepted | Assuming you intended Bto 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 Bactually does override f(), then the former calls the override, whereas the latter calls the function in Aregardless.
|
相关文章推荐
- Why does this code using `::boost::bind` get a compiler error?
- Why does a destructor in base class need to be declared virtual?
- Why does metamodeling recently get so much attention?
- Why do I get the error "The target GatherAllFilesToPublish does not exist"?
- Why does DOS use 100% CPU under Virtual PC?
- Why destruct function should always virtual
- Why do I get the error "The target GatherAllFilesToPublish does not exist"?
- Why do we get error "Call to undefined function: ora_logon()/ ocilogon()"?
- Why does DOS use 100% CPU under Virtual PC?
- httpModules remove does not work in a folder or virtual directory
- 类成员指针 error C2064: term does not evaluate to a function
- 关于在64位win7下运行Virtualbox安装系统时提示出错Unable to load R3 module D:\VirtualBox/VBoxDD.DLL (VBoxDD): GetLastE
- [iOS_Dev] distribute App on App Store via Virtual Mac ?NO and see Why.
- fgetc和getc的区别 The function getchar is defined to be equivalent to getc(stdin). The difference betwee
- 'MessageBoxA' : function does not take 1 parameters
- "Pure Virtual Function Called": An Explanation翻译
- Why Not Specialize Function Templates?
- effective c++ 条款9 do not call virtual function in constructor or deconstructor
- a missing vtable usually means the first non-inline virtual member function has no definition.
- Genymotion does not start Android virtual device