composition vs inheritance

Steven Schveighoffer schveiguy at yahoo.com
Wed Mar 16 05:19:54 PDT 2011


On Wed, 16 Mar 2011 08:01:46 -0400, spir <denis.spir at gmail.com> wrote:

> composition vs inheritance
>
> I have carefully read the document "Prefer composition to inheritance",  
> from C++ coding standards, at
> http://www.artima.com/cppsource/codestandards3.html, by Herb Sutter and  
> Andrei Alexandrescu.
>
> In general, I do agree in that composition makes for a simpler scheme,  
> and more flexible. But when writing D code, I constantly step on the  
> same issue that without inheritance and (runtime type) polymorphism, I  
> simply cannot express /very/ common things.
> For instance, say I have 3 kinds of Xs X1 X2 X3. I would like to write:
>
> void moveTogether (X[] xs, Vector vector) {
>      foreach (x ; xs) {
>          lookAround(x);
>          x.move(vector);
>
>          if (isX3(x)) {
>              writeln(x.motto);
>              x.jump();
>          }
>      }
> }
>
> void lookAround (X x) {...}
>

 From the article: "Of course, these are not arguments against inheritance  
per se. Inheritance affords a great deal of power, including  
substitutability and/or the ability to override virtual functions."

i.e., use inheritance because your design requires it.

-Steve


More information about the Digitalmars-d mailing list