Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cost of Virtual-and-final function at base class (vtable/virtual-cost)

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.

  • What's the point of a final virtual function?
  • Does the cost of virtual functions increase with the number of classes in the inheritance tree?
  • http://en.cppreference.com/w/cpp/language/final
like image 432
javaLover Avatar asked Oct 19 '25 02:10

javaLover


1 Answers

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.

like image 181
Edgar Rokjān Avatar answered Oct 21 '25 16:10

Edgar Rokjān



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!