Is there any sense in marking a base class function as both virtual and final? [duplicate]

喜欢而已 提交于 2019-12-01 03:27:26

Is there any sense in marking a base class function as both virtual and final?

Yes, at least temporarily.

I found myself in a relatively large and unfamiliar existing C++ source code base. Much of the code was written prior to C++11. I found that I wanted to ensure that all overrides of a virtual function in a base class were marked with override. The hard part is locating all of those overrides.

I marked the virtual function in the base class with final, and the compiler quickly showed me where every single override was declared. It was then very easy to decorate the overrides how I wanted, and remove the final from the virtual in the base class.

You can mark it virtual to indicate that it is 'virtual' in the class you are inheriting from (even though you don't have to do this), and mark it final to indicate that no class deriving from your class may override it further. This may happen when you are implementing an abstract base class, for example. This is C++11, so it's not useful; override is a much better indication, since it is enforced by the compiler.

Another possibility: you want this method not to be overridden, but you want to be able to change that without recompilation. Remember that virtual means it is in the virtual table. even if the compiler will not let you override it.

I think the purpose of the example you have shown is to demonstrate priorities between virtual and final, and nothing more. It is a minimal use of final, not a useful one.

Marking a non-virtual method as final makes no sense, since you cannot override them anyway. If you want the compiler to prevent hiding, that is a completely different issue, that has nothing to do with the method being final. In a sense, non-virtual methods are final already, but hidable.

The alternative is a non-virtual function. But non-virtual function can be hidden by a derived class. So if you want to prevent a function hiding, it can be specified as virtual final one.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!