Thread overview
alias this
Nov 22, 2013
Mf_Gh
Nov 22, 2013
Jonathan M Davis
Nov 22, 2013
Mf_Gh
November 22, 2013
hi, i started to play a round with D and try to do something like:

class A{
	string a = "alias A";
	alias a this;
}

class B:A{
	string b = "alias B";
	alias b this;
}


void main() {
	A b = new B();
	writeln(b); //outputs alias A
}

i thought the output would be "alias B". why isn't the alias taken from the runtimetype?
November 22, 2013
On Friday, November 22, 2013 11:21:35 Mf_Gh wrote:
> hi, i started to play a round with D and try to do something like:
> 
> class A{
> 	string a = "alias A";
> 	alias a this;
> }
> 
> class B:A{
> 	string b = "alias B";
> 	alias b this;
> }
> 
> 
> void main() {
> 	A b = new B();
> 	writeln(b); //outputs alias A
> }
> 
> i thought the output would be "alias B". why isn't the alias taken from the runtimetype?

Because there's no virtual function involved. There's nothing virtal about either a or b. They're just variables. You'd need to alias to a virtual function if you wanted polymorphic behavior. e.g. something like

class A{
        string a = "alias A";
        string get() { return a; }
        alias get this;
}

class B:A{
        string b = "alias B";
        override string get() { return b; }
        alias get this;
}


void main() {
        A b = new B();
        writeln(b); //outputs alias A
}


- Jonathan M Davis
November 22, 2013
thx