Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I avoid dynamic_cast in my C++ code?
    text
    copied!<p>Let's say I have the following class structure:</p> <pre><code>class Car; class FooCar : public Car; class BarCar : public Car; class Engine; class FooEngine : public Engine; class BarEngine : public Engine; </code></pre> <p>Let's also give a <code>Car</code> a handle to its <code>Engine</code>. A <code>FooCar</code> will be created with a <code>FooEngine*</code> and a <code>BarCar</code> will be created with a <code>BarEngine*</code>. Is there a way to arrange things so a <code>FooCar</code> object can call member functions of <code>FooEngine</code> without downcasting?</p> <p>Here's why the class structure is laid out the way it is right now:</p> <ol> <li>All <code>Car</code>s have an <code>Engine</code>. Further, a <code>FooCar</code> will only ever use a <code>FooEngine</code>.</li> <li>There are data and algorithms shared by all <code>Engine</code>s that I'd rather not copy and paste.</li> <li>I might want to write a function that requires an <code>Engine</code> to know about its <code>Car</code>.</li> </ol> <p>As soon as I typed <code>dynamic_cast</code> when writing this code, I knew I was probably doing something wrong. Is there a better way to do this?</p> <p>UPDATE:</p> <p>Based on the answers given so far, I'm leaning towards two possibilities:</p> <ol> <li>Have <code>Car</code> provide a pure virtual <code>getEngine()</code> function. That would allow <code>FooCar</code> and <code>BarCar</code> to have implementations that return the correct kind of <code>Engine</code>.</li> <li>Absorb all of the <code>Engine</code> functionality into the <code>Car</code> inheritance tree. <code>Engine</code> was broken out for maintenance reasons (to keep the <code>Engine</code> 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.</li> </ol> <p>Is there a strong community preference for one of these solutions? Is there a third option I haven't considered?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload