Composition is better than inheritance


#1

Why ?


#2

There are lots of good reasons. I guess the main one is looser coupling.

An important reason for me is readability: If you inherit from a bunch of classes and call some methods on them, you can’t always tell by reading the code which base class a method applies to. But if you use composition, then all your calls will specify their object, and be more readable.


#3

The main place I find it awkward is callbacks. Then you end up with a subclass and composition, which seems to be incrementally more to grok.

One of my favorite things about Juce was always the judicious use of multiple inheritance - it felt like the way C++ was ‘meant to work’.

Bruce


#4

Callbacks are exactly what inheritance is there for! If you need to override a virtual method, then inherit; otherwise, don’t!