Weird behavior of "this" in a subclass, I think?

Daniel Kozák via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 15 23:05:51 PDT 2015


On Thu, 16 Jul 2015 00:18:30 +0000
seashell86 via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com>
wrote:

> So I've been mostly just toying around with D as it seems like it 
> will end up being a strong language for game development both now 
> and even moreso in the future.  That being said, I'm perplexed by 
> using this code and not receiving the result I would imagine. 
> Here is the source code of a basic "sandbox.d" file:
> 
>      import std.stdio;
> 
>      class Animal {
>          string voice;
> 
>          void speak() {
>              writeln(this.voice);
>          }
>      }
> 
>      class Dog : Animal {
>          string voice = "Whoof!";
>      }
> 
>      int main() {
>          auto a = new Animal();
>          auto d = new Dog();
> 
>          a.speak(); // Prints ""
>          d.speak(); // Prints "" instead of "Whoof!"
> 
>          return 0;
>      }
> 
> I know that C++ behaves this way.  However, Dlang impresses me by 
> having a very "no duh" approach to things where this type of 
> example seems very "no duh."  Anyways, please be gentle as I am 
> hardly what most would consider a "skilled" programmer and, as 
> such, was something I wanted to bounce off the pros :)


You can use template this parametr

import std.stdio;

class Animal {
	string voice;

	void speak(this C)() {
		writeln((cast(C)this).voice);
	}
}

class Dog : Animal {
	string voice = "Whoof!";
}

int main() {
	auto a = new Animal();
	auto d = new Dog();

	a.speak(); // Prints ""
	d.speak(); // Prints "Whoof!"

	return 0;
}


More information about the Digitalmars-d-learn mailing list