Re: Overriding abstract class fields

2016-09-01 Thread slaid via Digitalmars-d-learn

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!



Overriding abstract class fields

2016-09-01 Thread slaid via Digitalmars-d-learn

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