Yeah it’s best to avoid
dynamic_cast as much as possible. Ask yourself what you want to do with those planes, here is a few ideas:
- You could use a separate list of
Plane, and make the
Planethemselves register or unregister inside this list. Why matter with those
Peasants where you can directly talk to their
- Things is you have to maintain this separate list, and you need a system to make the
Planes register themselves in that list. And unregister when they’re removed from the game!
- If you only ever deal with a lone
Plane, well, just keep it as a pointer somewhere and use it directly!
- The most efficient of all, except you can only have one
- You could use a generic signal system, based on something like
virtual void sendSignal(unsigned signalCode). Only
Batmananswers to the Bat-Signal, right? You can do the same with
Planes. Plus you get to reuse this system for other stuff, like a self-destruct (game-wise) button for some secret base (e.g.
- That means you have to get some method
void dispatchSignal(unsigned signalCode)that will dispatches it to every active
- You can combine it with #1, with a list per signal-code. Thus, no useless
Planes aren’t going to receive the Bat-Signal this way and
Batmanwon’t receive the
SECRET_DESTRUCTION_SIGNAL. Or maybe he will, because he might have someone left to rescue?
- You could use type for the signal of course.
unsignedare just generic, but a
struct enumcould provide additional checks and restrictions!
- You could also use something more polluting: a method
virtual Plane* asAPlane()that, for
Plane-Derived, gives you
nullptrfor the rest of
- It’s polluting because if you need to do that for more than one class, you’re going to have a lot of those “casting” methods.
- You’ll end up having to check every active
GameObjtoo. If you got a lot of
Plane, that’s probably OK. If you only have 1 for 100
GameObjs, you’re going to do 99 checks for nothing.
All of those are much quicker than a dynamic cast and none requires the RTTI.