2

I came across the concept of interitence vs composition and did a bit of reading(mostly on the internet). So summarizing what I've learned.

Using inheritence can make your life easier since you do not have to re-implement the behaviors that does not need to change (not be overwritten). But if the behavior of the class grows / need changing, it can be a pain since you have to go through all of the classes that ahs overwritten a function from the base class.

Composition, on the other hand, keeps its component as a member variable, so there isnt a lot of dependency compared to inheritences.

My first question is, am I missing any important things in terms of pros and cons of either inheritence or composition?

And secondly, what are some examples where you would prefer one over another? The only one that I can think of is, 'if you need to inherit multiple classes, I should use composition instead of inheritences'. Or is it more subjective on when to use what?

dwnenr
  • 443
  • 1
  • 4
  • 15
  • It sounds like you have the general concepts right. In C++, inheritance is implemented *under the hood* as composition. You should prefer whatever works for you. – Drew Dormann Aug 16 '15 at 05:00

0 Answers0