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

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

    Supplement to Mario Knezović 's answer:

    class IA
    {
    public:
      virtual int getNum() const = 0;
    };
    
    class BaseA : public IA
    {
    public:
     inline virtual int getNum() const final {return ...};
    };
    
    class ImplA : public BaseA {...};
    
    IA* pa = ...;
    ...
    ImplA* impla = static_cast(pa);
    
    //the following line should cause compiler to use the inlined function BaseA::getNum(), 
    //instead of dynamic binding (via vtable or something).
    //any class/subclass of BaseA will benefit from it
    
    int n = impla->getNum();
    

    The above code shows the theory, but not actually tested on real compilers. Much appreciated if anyone paste a disassembled output.

提交回复
热议问题