RTTI — Asking a Type at Run Time
Run-time type information lets code holding a base-class pointer or reference discover the real derived type of a polymorphic object, using dynamic_cast and typeid.
Inspect polymorphic types with typeid and dynamic_cast, including a failed cast.
Rocket Run keeps every enemy in one list of Enemy* pointers: drones, asteroids and the occasional boss. When the player lands a hit, the boss must move to its next phase, but a drone has no phases. The code holds a plain Enemy*. How can it find out what the object really is? That is what run-time type information, or RTTI, is for.
The rule
RTTI lets a base pointer ask which derived type it really points to.
A derived class is a more specific kind of its base class:
struct Enemy {
virtual ~Enemy() = default; // virtual: Enemy is now polymorphic
int health = 10;
};
struct Boss : Enemy { int phase = 1; };
struct Drone : Enemy {};RTTI works only for polymorphic classes: those with at least one virtual function. The virtual destructor above is enough. With that in place you have two tools:
dynamic_cast converts to the derived type if the object really is one:
void onHit(Enemy* enemy) {
if (auto* boss = dynamic_cast<Boss*>(enemy)) {
++boss->phase; // only for bosses
}
}With a pointer, a failed cast returns nullptr. With a reference, dynamic_cast<Boss&>(e), a failure throws std::bad_cast, since there is no null reference.
typeid (header <typeinfo>) compares exact types: typeid(*enemy) == typeid(Boss). Its .name() text is implementation-defined; GCC, for instance, prints a mangled name, so use it only for debugging.