3

Consider the following:

class foo
{
public:
    virtual void bar() final {}
};

In order to prevent bar from being redeclared in a child class, one may use a virtual final. Is this a good idea? Will this come at the cost of runtime overhead, even with optimization on? What if there's already a virtual table, will its size be extended to have bar?

1 Answers1

0

I found the question since I had the same idea - so I think it's a good idea.

Answering the questions for VS 2017 (based on reading disassembly):

  • No runtime overhead, even in debug-mode. Just a normal function call.
  • Adds overhead of v-table (with an entry in the vtable for the function; so if you already have virtual functions the overhead is very small).
  • As intended it will detect the case of someone attempting to add void bar() in a derived class.

One specific use case is if you are refactoring and the function was virtual and you want to remove it or make it non-virtual.

The remove-part is also found in one answer to the related (not duplicate) question: What's the point of a final virtual function?

However, it seems it was not considered in: http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rh-override and thus you might have to justify it in code review.

Hans Olsson
  • 11,123
  • 15
  • 38