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

后端 未结 10 2010
故里飘歌
故里飘歌 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:54

    Final keyword in C++ when added to a function, prevents it from being overridden by a base class. Also when added to a class prevents inheritance of any type. Consider the following example which shows use of final specifier. This program fails in compilation.

    #include 
    using namespace std;
    
    class Base
    {
      public:
      virtual void myfun() final
      {
        cout << "myfun() in Base";
      }
    };
    class Derived : public Base
    {
      void myfun()
      {
        cout << "myfun() in Derived\n";
      }
    };
    
    int main()
    {
      Derived d;
      Base &b = d;
      b.myfun();
      return 0;
    }
    

    Also:

    #include 
    class Base final
    {
    };
    
    class Derived : public Base
    {
    };
    
    int main()
    {
      Derived d;
      return 0;
    }
    

提交回复
热议问题