Let's say I have the following class structure:
class Car;
class FooCar : public Car;
class BarCar : public Car;
class Engine;
class FooEngine : public Engine;
class BarEngine : public Engine;
Let's also give a Car a handle to its Engine. A FooCar will be created with a FooEngine* and a BarCar will be created with a BarEngine*. Is there a way to arrange things so a FooCar object can call member functions of FooEngine without downcasting?
Here's why the class structure is laid out the way it is right now:
- All
Cars have anEngine. Further, aFooCarwill only ever use aFooEngine. - There are data and algorithms shared by all
Engines that I'd rather not copy and paste. - I might want to write a function that requires an
Engineto know about itsCar.
As soon as I typed dynamic_cast when writing this code, I knew I was probably doing something wrong. Is there a better way to do this?
UPDATE:
Based on the answers given so far, I'm leaning towards two possibilities:
- Have
Carprovide a pure virtualgetEngine()function. That would allowFooCarandBarCarto have implementations that return the correct kind ofEngine. - Absorb all of the
Enginefunctionality into theCarinheritance tree.Enginewas broken out for maintenance reasons (to keep theEnginestuff in a separate place). It's a trade-off between having more small classes (small in lines of code) versus having fewer large classes.
Is there a strong community preference for one of these solutions? Is there a third option I haven't considered?