Calls to b are static - the compiler knows exactly the compile time what type of b will be at runtime (obviously Bar), so it will directly use the addresses of the methods that will be called.
A virtual question matters only when making a call using a pointer / link, because during a call, different goals can have different goals. It matters if, for example, you called function1 on a pointer and at runtime changed the actual type pointed to by the pointer.
Now the situation here, where you call function2 on f, is complicated for two reasons: the function is never redefined and you use a link that cannot be reassigned. Thus, a really smart compiler that sees all the input files can understand that the purpose of the call will really be with 100% trust (since you are not going to add new classes to already compiled code). However, AFAIK, compilers should not do this for you to pay the costs.
Generally speaking, if you do not plan to redefine any function, do not make it virtual.
source share