How do I use composition with inheritance?

前端 未结 10 2398
星月不相逢
星月不相逢 2021-02-09 04:41

I\'m going to try to ask my question in the context of a simple example...

Let\'s say I have an abstract base class Car. Car has-a basic Engine object. I have a method

10条回答
  •  难免孤独
    2021-02-09 05:14

    don't expose the internals of your class in the interface - in other words, the public method of Car should be Start, not StartEngine

    if you want to impose an internal structure (i.e. like having only 1 engine) then you need another abstract/base class Engine that can be specialized.

    then you can construct a sports car out of parts by setting the m_engine member to a sporty subclass of Engine, et al

    EDIT: note that in the real world, a turbocharger is not part of the engine, it is an add-on to the engine, with its own control interface... But if you want to include things like this in your ferrari engine, that's ok, just upcast in the SportsCar subclass to make your base Engine into a TurboEngine

    but it would be better modeling to keep the components separate - that way you can upgrade your turbocharger (dual intake vs single intake, for example) without replacing the entire engine!

提交回复
热议问题