Getting "this" to work similar to "self" in Python
John Colvin via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jul 23 01:21:22 PDT 2015
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...
More information about the Digitalmars-d-learn
mailing list