Overriding of inherited class static methods?
ShadoLight
ettienne.gilbert at gmail.com
Wed Jul 22 14:03:53 UTC 2026
On Wednesday, 22 July 2026 at 12:04:36 UTC, Denis F wrote:
>
> Your sample lack of override keyword on D.foo definition. I
> think this can be used to differentiate such cases.
OK, so you are proposing this:
```D
class B {
public static int foo(int x) {
return 2*x;
}
}
class D : B {
public static override int foo(int x) {
return 3*x;
}
}
```
This cannot work as static function addresses are not specified
in the vtable, hence they cannot be overridden. This will also be
a breaking change as, currently, you can call a static function
through the instance pointer or the class name like this:
```D
D b = new D;
assert(b.foo(2) == D.foo(2));
```
Both ```b.foo(2)``` and ```D.foo(2)``` calls here are equivalent
and call the same "free function" ```foo``` (without the need for
the ```this``` pointer to be passed implicitly).
If you then propose to add static functions to the vtable to
allow them to be overridden - that would then in turn cause
static functions not to be callable using the class name
(```D.foo(..)``` above) as the vtable is associated with the
instance of the class (which is passed via the implicit
```this``` pointer), and not the class definition. In such a case
which instance of D does ```D.foo(..)``` refer to?
This would also mean static functions will have to be called, as
is the case for virtual functions today, through an extra
indirection (compared to normal static functions today) - with
performance implications if you go from "static" to "static
override".
In fact they would then become practically indistinguishable from
virtual functions itself.
There are other issues as well, for example can a "static
override" method access a static data member of a class?
This would change the concept of "static functions" in D to be
completely different to the classical concept that all object
oriented languages (Java, C++, C#, D,...) share. I literally
cannot imagine that you will get any support for this idea.
Static methods are quite simply "free functions" with a slightly
modified calling syntax (and affected by the visibility and
access rules of their "owner" class, etc...).
More information about the Digitalmars-d
mailing list