Overriding of inherited class static methods?

ShadoLight ettienne.gilbert at gmail.com
Fri Jul 24 08:09:14 UTC 2026


On Thursday, 23 July 2026 at 21:07:32 UTC, monkyyy wrote:

> my understanding of what op wants is this:
>
> ```d
> import std;
>
> interface base{
>     static int foo(int);
> }
> class A:base{
>     static int foo(int i)=>i+2;
> }
> class B:base{
>     static int foo(int i)=>i*2;
> }
> unittest{
>     base bar=new A();
>     auto f=&bar.foo;
>     f(3).writeln;
> }
> ```
Having a static method declared in a interface and then 
'implementing' it in a derived class is not really 'overriding' 
in the context of this question. What the OP is saying/implying 
is this:

```D
import std;

class base{
     static int foo(int i)=>i+1;
}
class A:base{
     static override int foo(int i)=>i+2;   //This is the request 
i.e. add polymorphic
                                            // behavior here
}
class B:base {
     static int foo(int i)=>i*2;            //This already works, 
but not polymorphically
}
unittest{
     base b1=new A();
     assert(b1.foo(2) == 4);    // Polymorphic behavior... not 
currently possible
     base b2=new B();
     assert(b2.foo(2) == 3);    // Not polymorphic behavior... 
this currently works
}
```

There are a lot of issues with this. For example, what should 
happen here?

```D
class base{
     static int count;
     static int foo(int i)=>count+1;
}
class A:base{
     static override int foo(int i)=>count+2;   //This is the 
request i.e. add polymorphic
                                            // behavior here
}

unittest{
     base b1=new A();
     int x = b1.foo(2);
}
```
How would you handle a static member like ```count``` now?

Then these is the issue of calling the static method through the 
name i.e. if you have multiple instances of type A...
```D
base b1 = A(), b2 = A();
```
...how is ```A.foo(2)``` handled in this case ... which instance 
does it refer to?

I don't think adding polymorphic behavior to static methods can 
be done in a way that is sensible - it will be massively 
confusing.



More information about the Digitalmars-d mailing list