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
Car
s have anEngine
. Further, aFooCar
will only ever use aFooEngine
. - There are data and algorithms shared by all
Engine
s that I'd rather not copy and paste. - I might want to write a function that requires an
Engine
to 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
Car
provide a pure virtualgetEngine()
function. That would allowFooCar
andBarCar
to have implementations that return the correct kind ofEngine
. - Absorb all of the
Engine
functionality into theCar
inheritance tree.Engine
was broken out for maintenance reasons (to keep theEngine
stuff 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?