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 thePlane
themselves register or unregister inside this list. Why matter with thosePeasant
s where you can directly talk to theirBoss
es?
- Things is you have to maintain this separate list, and you need a system to make the
Plane
s 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
Plane
of course.
- You could use a generic signal system, based on something like
virtual void sendSignal(unsigned signalCode)
. OnlyBatman
answers to the Bat-Signal, right? You can do the same withPlane
s. Plus you get to reuse this system for other stuff, like a self-destruct (game-wise) button for some secret base (e.g.sendSignal(SECRET_DESTRUCTION_SIGNAL)
).
- That means you have to get some method
void dispatchSignal(unsigned signalCode)
that will dispatches it to every activeGameObj
. - You can combine it with #1, with a list per signal-code. Thus, no useless
sendSignal
calls, andPlane
s aren’t going to receive the Bat-Signal this way andBatman
won’t receive theSECRET_DESTRUCTION_SIGNAL
. Or maybe he will, because he might have someone left to rescue? - You could use type for the signal of course.
unsigned
are just generic, but astruct enum
could provide additional checks and restrictions!
- You could also use something more polluting: a method
virtual Plane* asAPlane()
that, forPlane
s andPlane
-Derived, gives you*this
, andnullptr
for the rest ofGameObjs
.
- 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
GameObj
too. If you got a lot ofPlane
, that’s probably OK. If you only have 1 for 100GameObj
s, you’re going to do 99 checks for nothing.
All of those are much quicker than a dynamic cast and none requires the RTTI.