Search code examples
ddmd

Overriding 'package' member functions in D


I have a member function in a class with the package protection attribute and I want to override it in a subclass, in the same package, different module. The dmd compiler shouts that I cannot override a non-virtual function. If I make the function public, it actually works.

Why a package function is not virtual?

Example code:

module test.A;
class A {
  package void doSomething() {}
}

module test.B;
import test.A;
class B : A {
  package override void doSomething() {} // ERROR! overriding a non-virtual function
} 

Solution

  • public and protected functions are always virtual unless the compiler decides that it can optimize them so that they're non-virtual (which can only happen if you mark them as final, and they don't override anything). Some specific calls to virtual functions might be optimized to non-virtual if the compiler can guarantee the exact type of the object, but that's not likely to happen often given that it's relatively rare that you can know the exact type of an object (generally only right after creating it with new), and dmd generally eschews flow analysis.

    private and package are never virtual.

    The online documentation does imply that you can overload package, but this is definitely not what the compiler does, and I'm 99.99% certain that the current behavior is the intended behavior and will always be the behavior. I'm trying to verify that on the D newsgroup though.