Is there a way to ensure that member functions are virtual in D?

As I understand it, all member functions are virtual in D but the compiler is free to make functions non-virtual if it sees that they are never overridden.

What I’m not clear on is what happens when you compile a module in which member functions are not overridden and then import that module somewhere else where you override a member function. I don’t think it re-compiles the original module. Does it simply assume that any member function with external linkage is virtual?

Best Answer:

All D member functions are virtual by default. I don’t think there’s any compilers out there that actually make functions non-virtual as an optimization. You can do it manually though, by marking the class or the function as “final”.

Other Answer 1:

FeepingCreature is mostly correct except for templated functions which cannot be made virtual.

Other Answer 2:

How this is implemented is compiler- and linker-specific. But one common situation where virtual function calls can be optimized away, is when you have a class instantiated locally. Then function calls can be performed directly within this scope, because the type of the class is fully known at compile time. This can be done on a compiler level.

Besides this, if the linker realizes function implementation is never overridden, then the linker might do the optimization and replace virtual function calls with direct function calls on that class. In particular, if a class is never derived, then all calls to member functions can be performed directly. It’s as if the linker would insert the ‘final’ keyword whereever possible. (The linker may not apply this optimization to exported classes and functions, since the linker does not know if functions are overriden in other libraries or executables.)

Other Answer 3:

I believe FeepingCreature is correct, but in addition I think you can assume that such optimizations only will be considered by the compiler if it directly creates an executable from the sources.