Inheritance is quickly losing its popularity among modern programming languages but it’s still supported and heavily used in many C++ projects. Fortunately, in C++ inhertiance doesn’t always involve overhead - without virtual dispatch, compiler is able to select the right method address to invoke at compile time and perform usual optimizations. So for the following source code
we get the optimal assembly
But what happens in case m is virtual?
we can clearly see 2 virtual calls in clang
GCC generates a special case for handling Grandchild method m
but it’s still far from the optimal assembly we had without virtual dispatch.
So is it all doom and gloom? Well, if we don’t plan on extending Grandchild class to override its method m, we can mark it final
and get a much better assembly in both GCC and clang
Given that C++ supports a number of alternatives for inheritance, e.g. CRTP, composition, it’s always a good idea to consider them, but if nothing else works, consider using final for all methods you don’t plan on overriding.
Just for the record, I'm on the camp that likes finals both on the vir func as well as class leafs. I know this is not the most populate approach but I really like to minimize inheritance as much as possible.