How polymorphism work in D?

ShadoLight ettienne.gilbert at gmail.com
Wed Nov 6 17:47:44 UTC 2019


On Wednesday, 6 November 2019 at 06:27:32 UTC, OiseuKodeur wrote:
> 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
>>> 
[snip]

Rikki's answer is the direct answer to your question since you 
already had the if(..) statements coded in your main function, 
but your code does not really exploit the main abstraction 
advantage that polymorphism offers.

The typical use of polymorphism in terms of your example would be 
where you don't want to mess with the interior details of derived 
classes in your main function - you want to code your logic in 
your main function just keeping the 'interface' as defined by Foo 
in your head. Something like this:

abstract class Foo {
     void writeProp();
}

class Bar : Foo
{
     float value;

     this(float t_value) { value = t_value; }

     override void writeProp() {value.writeln;}
}

class Baz : Foo
{
     string name;

     this(string t_name) { name = t_name; }

     override void writeProp() {name.writeln;}
}

void main()
{
     Foo foo = new Bar(10);

     foo.writeProp;
     foo.writeln;
}

The idea is that you can separate Baz and Bar "out of sight" (in 
a library for example) and write your main logic i.t.o. only 
Foo's.

The advantage will become apparent if you want to add another 
class, say Boo : Foo. In your case you would need to add another 
else if(..) clause to your main function in addition to adding 
the class itself. In the above case you only need to add the 
class - you don't need to touch the main function.




More information about the Digitalmars-d-learn mailing list