Overriding of inherited class static methods?
ShadoLight
ettienne.gilbert at gmail.com
Wed Jul 22 09:13:59 UTC 2026
On Wednesday, 22 July 2026 at 08:05:48 UTC, Denis F wrote:
>
> And, as shown above, this could work, right?
This would depend what you want to achieve.
>
> And it would be good from a code maintenance point: if a method
> could easily be converted to static or vice versa during the
> code's lifetime it will be convient, I think
>
"converting to static or vice versa ... easily" comes with some
'gotcha's' you have to keep in mind. Consider a class D
inheriting from a class B:
```D
class B {
public int foo(int x) {
return 2*x;
}
}
class D : B {
public override int foo(int x) {
return 3*x;
}
}
```
Consider what the idea behind polymorphic behavior is i.e. for
example, lets create 2 instances of class D, but with one being
of the base "type"...
```D
B b = new D;
D d = new D;
```
...and both cases will call the overridden foo function:
```D
assert(b.foo(2)==6); //PASS
assert(d.foo(2)==6); //PASS
```
Now consider what happens if you convert foo from virtual to
static:
```D
class B {
public static int foo(int x) {
return 2*x;
}
}
class D : B {
public static int foo(int x) {
return 3*x;
}
}
```
If you keep the rest of the code the same...
```D
B b = new D;
D d = new D;
assert(b.foo(2)==6); //FAIL
assert(d.foo(2)==6); //PASS
```
... instance b will call it's own version of foo, and the assert
will fail.
TLDR: Changing a virtual method from virtual to static or vice
versa can (and probably will) affect downstream code.
More information about the Digitalmars-d
mailing list