Is there any vtable/virtual cost for a virtual final function (final
at base class)?
class B{
public: virtual void fFinal() final{ .... do something ..... }
public: void fCheap() { .... do something ..... }
public: virtual void fVirtual() { .... do something ..... }
};
class C : public B{
public: virtual void fVirtual() { .... do something ..... }
};
Will the cost of fFinal()
= cost of fCheap()
or fVirtual()
?
I am going to use final+virtual to prevent human-error ("Don't override me").
fCheap()
is not so safe, because I can still hide the parent's function.
These below links don't provide answer.
As far as I can tell, it is unspecified how virtual functions mechanism is implemented by any particular compiler. It is most likely that they put a pointer to vtable into the class if it has at least one virtual function even if this virtual function is marked as final.
I've tested a simplifed example based on your code snippet:
class Base {
public:
virtual void foo() final {}
};
static_assert(sizeof(Base) > 1, "No pointer to vtable");
Seems that both gcc 6.3 and clang 4.0 add a pointer to vtable.
It means that the rules which govern usual virtual functions apply for a function which marked both virtual and final in the base class. As a consequence, Base
class grows in size and, and when you call foo
via the pointer/reference to Base
class or some class derived from Base
, you pay some additional cost for being redirected through the vtable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With