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

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

    Final cannot be applied to non-virtual functions.

    error: only virtual member functions can be marked 'final'
    

    It wouldn't be very meaningful to be able to mark a non-virtual method as 'final'. Given

    struct A { void foo(); };
    struct B : public A { void foo(); };
    A * a = new B;
    a -> foo(); // this will call A :: foo anyway, regardless of whether there is a B::foo
    

    a->foo() will always call A::foo.

    But, if A::foo was virtual, then B::foo would override it. This might be undesirable, and hence it would make sense to make the virtual function final.

    The question is though, why allow final on virtual functions. If you have a deep hierarchy:

    struct A            { virtual void foo(); };
    struct B : public A { virtual void foo(); };
    struct C : public B { virtual void foo() final; };
    struct D : public C { /* cannot override foo */ };
    

    Then the final puts a 'floor' on how much overriding can be done. Other classes can extend A and B and override their foo, but it a class extends C then it is not allowed.

    So it probably doesn't make sense to make the 'top-level' foo final, but it might make sense lower down.

    (I think though, there is room to extend the words final and override to non-virtual members. They would have a different meaning though.)

提交回复
热议问题