On Wednesday, 22 July 2015 at 22:52:22 UTC, John Colvin wrote:
On Wednesday, 22 July 2015 at 22:22:02 UTC, nurfz wrote:
[...]

Fields of classes are not in any way polymorphic in D (this is the same as C++ and I think java too). Base class members can be accessed like so:

class Vehicle {
    int speed;
    void printSpeed() {
        writeln(this.speed);
    }
}

class Airplane: Vehicle {
    this()
    {
        Vehicle.speed = 100;
    }
}

or if you really want to use the same variable name:

class Airplane: Vehicle {
    alias speed = Vehicle.speed;
    this()
    {
        speed = 100;
    }
}

You can even automatically do that sort of thing by various means, the shortest/simplest way I can think of would be:

class Airplane: Vehicle {
    private @property Vehicle base() { return this; }
    alias base this;
    this()
    {
        speed = 100;
    }
}

Ok literally ignore all of that, I'm an idiot.

speed is accessible directly, without Vehicle prefix, both from inside Airplane and outside. However, if you declare another variable Airplane.speed, it will shadow* Vehicle.speed, leading to the behaviour you see. Use a constructor instead of declaring a new variable with the same name.

*as opposed to override or aliasing


It really shows how little I use classes in D...

Reply via email to