What is the purpose of the “final” keyword in C++11 for functions?

后端 未结 10 1995
故里飘歌
故里飘歌 2020-12-02 05:31

What is the purpose of the final keyword in C++11 for functions? I understand it prevents function overriding by derived classes, but if this is the case, then

10条回答
  •  [愿得一人]
    2020-12-02 05:41

    "final" also allows a compiler optimization to bypass the indirect call:

    class IAbstract
    {
    public:
      virtual void DoSomething() = 0;
    };
    
    class CDerived : public IAbstract
    {
      void DoSomething() final { m_x = 1 ; }
    
      void Blah( void ) { DoSomething(); }
    
    };
    

    with "final", the compiler can call CDerived::DoSomething() directly from within Blah(), or even inline. Without it, it has to generate an indirect call inside of Blah() because Blah() could be called inside a derived class which has overridden DoSomething().

提交回复
热议问题