Can inheritance be replaced completely by composition?

后端 未结 4 1395
北海茫月
北海茫月 2020-12-28 23:22

This question is NOT question like \"inheritence vs composition\".

I understand completely how inheritance differs from composition, I know the Lisk

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 23:50

    Nice question ...

    You may want to prefer inheritance over composition when you want to distinguish semantically between "A is a B" and "A has a B". E.g. class Car may have an Engine member (composition), but may be (i.e. inherit from) a Vehicle.

    I think the distinction plays out in having to maintain the number of methods shared by your two classes. When you inherit, you only need to override those (virtual) functions in the base class that you really need to; if you were to use purely composition, you'd need to re-implement every method of your member class that's public.

    Ultimately, the "best" method is the one that is most suitable for your current application.

    Edit:

    There's a small but succinct debate about it here: http://www.sitepoint.com/forums/showthread.php?568744-When-to-use-inheritance

    as well as a Wikipedia article(!) about it: http://en.wikipedia.org/wiki/Composition_over_inheritance#Drawbacks

提交回复
热议问题