How polymorphism work in D?

OiseuKodeur oiseaukodeur at gmail.com
Wed Nov 6 06:27:32 UTC 2019


On Wednesday, 6 November 2019 at 06:05:25 UTC, rikki cattermole 
wrote:
> On 06/11/2019 6:43 PM, OiseuKodeur wrote:
>> I have this
>> 
>> ```
>> import std.stdio : writeln;
>> 
>> abstract class Foo { }
>> 
>> class Bar : Foo
>> {
>>      float value;
>> 
>>      this(float t_value) { value = t_value; }
>> }
>> 
>> class Baz : Foo
>> {
>>      string name;
>> 
>>      this(string t_name) { name = t_name; }
>> }
>> 
>> void main()
>> {
>>      Foo foo = new Bar(10);
>> 
>>      if (/* typeof foo == Bar */)
>
> if (Bar bar = cast(Bar)foo)
> 	bar.value.writeln;
>
>>          foo.value.writeln;
>>      else if (/* typeof foo == Baz */)
>
> else if (Baz baz = cast(Baz)foo)
> 	baz.name.writeln;
>
>>          foo.name.writeln;
>> 
>>      foo.writeln;
>> }
>> ```
>> 
>> I don't understand how i can differentiate between Bar and Baz 
>> and to get their attributes

thanks a lot


More information about the Digitalmars-d-learn mailing list