Thread overview
Overriding abstract class fields
Sep 01, 2016
slaid
Sep 01, 2016
Basile B.
Sep 01, 2016
slaid
September 01, 2016
I have a snippet:

  import std.stdio;
  import std.algorithm;

  abstract class A {
      int height = 0;
  }

  class B : A {
  }

  class C : A {
      int height = 1;
  }

  void main() {
      A[][int] list;
      list[0] = new A[](0);
      list[0] ~= new B();
      list[0] ~= new C();
      list[0] ~= new B();
      writeln(list[0].map!(x=>x.height));
  }

The output of this is [0, 0, 0] when if height was overridden it should print [0, 1, 0]. This is a trivial case for simplicity of the question, but in my actual code, I am trying to use the height field for sorting the A[] list (or reducing with max to get the object with the max height), but since they're all 0, none of the sorting occurs.

How do I override this height field?

Thanks
September 01, 2016
On Thursday, 1 September 2016 at 11:09:18 UTC, slaid wrote:
> I have a snippet:
>
> How do I override this height field?
>
> Thanks

The field height is not overridden. In C you have two "height". Since your array is of type A[], map takes A.height.

abstract class A
{
    int height = 0;
}

class B : A {}

class C : A
{
    int height = 1;
}

void main()
{
    writeln((new C).height); // prints 0, the height of C
    writeln((cast(A)(new C).height); // prints 1, the height of A
}

Only methods are virtual. To solve the problem you can create a virtual getter:

°°°°°°°°°°°°°°°°°°°°°°
abstract class A
{
    int height();
}

class B : A
{
    override int height(){return 0;}
}

class C : A
{
    override int height(){return 1;}
}
°°°°°°°°°°°°°°°°°°°°°°

But since height is only a field you can just use the same variable and set the value in the constructor (for example)

°°°°°°°°°°°°°°°°°°°°°°
abstract class A
{
    int height;
}

class B : A
{
    this(){height = 0;}
}

class C : A
{
    this(){height = 1;}
}
°°°°°°°°°°°°°°°°°°°°°°
September 01, 2016
On Thursday, 1 September 2016 at 11:34:28 UTC, Basile B. wrote:
> On Thursday, 1 September 2016 at 11:09:18 UTC, slaid wrote:
>> I have a snippet:
>>
>> How do I override this height field?
>>
>> Thanks
>
> The field height is not overridden. In C you have two "height". Since your array is of type A[], map takes A.height.
>
> Only methods are virtual. To solve the problem you can create a virtual getter:
>
> But since height is only a field you can just use the same variable and set the value in the constructor (for example)

Just what I needed, thanks a bunch!