2

Sorry, if there are errors in code. Currently writing from mobile.

Consider following scenario:

 class A
 {
       public:
       int funX()
       {
              return funY()*5;
       }
       virtual int funY() = 0;
 };

 class B : public A
//            public: A
 {
  public:
       int funY() override final
       {
            // implementation
       }
 };

 int foo(B& b)
 {
       return b.funX();
  };

In this code compiler has enough information to determine that it needs to call B::funY() without virtually calling it. However, it wouldn't be the case without the final keyword. Else one could send an instance of a possible class C that implements funY() differently.

Do the compliers optimize it away or not?

ALX23z
  • 4,456
  • 1
  • 11
  • 18
  • How about trying it out yourself, you can look at the assembly code generated for the version with and without the final keyword and see for yourself. I'd guess it will depend on the compiler and possibly optimization level used. – xception May 23 '19 at 08:26
  • If you want to know what a compiler does, [this is a useful tool](https://godbolt.org/z/9Kk42a). You can see that for instance GCC can do this from about version 4.7.1 and that the `final` keyword (probably) has no effect on its analysis, but is more for the user to be able to prevent errors. – Alex Celeste May 23 '19 at 08:29
  • 1
    oh, your code is wrong, should be `return b.funX();` instead in function `foo` – xception May 23 '19 at 08:32

0 Answers0