Distinct "static" parent property contents for children

Steven Schveighoffer schveiguy at yahoo.com
Thu Nov 9 14:34:10 UTC 2017


On 11/9/17 7:34 AM, Timoses wrote:

> 
> I suppose this is what Adam suggested, correct?

Yes, more or less. It's just an actual implementation vs. a description 
in case it wasn't clear.

> 
> 
> 
> This is a more general question: Why is it not possible to 
> implement/override static methods?

Static methods aren't virtual. There isn't a notion of a vtable for 
static methods on a class -- they are simply normal functions in a 
different namespace. I know other languages allow this, D does not.

> interface I // or abstract class I
> {
>      static int fun();

This is actually a non-virtual method, it needs an implementation.

> }
> class A : I
> {
>      static int fun() { return 3; }

Note, that this isn't necessary to implement I. In other words:

class A : I {}

also works.

> }
> void main()
> {
>      I i = new A();
>      i.fun();        // <--- linker error

This is calling I.fun, which has no implementation.

> }
> 
> or replacing interface with an abstract base class.
> 
> Static overriding would be quite interesting in terms of compile-time 
> handling of objects.

In a way, static overriding *does* work at compile time:

class A
{
   static int i() { return 1; }
}

class B : A
{
   static int i() { return 2; }
}

assert(A.i == 1);
assert(B.i == 2);

But what you are asking is to have an instance of B, even when 
statically typed as A, call the derived version of the static method. In 
essence, this is super-similar to a virtual method, but instead of 
taking an instance, it wouldn't need to. But the key here is you *need* 
an instance for it to make any sense.

It's not much different from what Adam and I suggested. The only thing 
you are missing is the ability to call the virtual member without an 
instance. But if you name your functions properly, and follow a 
convention, it will work for you.

-Steve


More information about the Digitalmars-d-learn mailing list