🔍 C++ RTTI – Know the Real Type at Runtime
RTTI stands for Run-Time Type Information. It helps you find out the actual type of an object while your program is running — like asking, “Hey, who are you really?” 🕵️♂️
RTTI is mainly useful when you’re dealing with inheritance and polymorphism.
✨ What RTTI Gives You
typeid
– tells you the type of an objectdynamic_cast
– safely casts pointers when using polymorphism
🔧 Example: Using typeid
#include <iostream> #include <typeinfo> using namespace std; class Animal { public: virtual void sound() {} }; class Dog : public Animal {}; int main() { Dog d; Animal* a = &d; cout << "Type of a: " << typeid(*a).name() << endl; return 0; }
🔧 Example: Using dynamic_cast
dynamic_cast
lets you check if a base class pointer can be safely converted to a derived class pointer.
#include <iostream> using namespace std; class Animal { public: virtual void sound() {} }; class Cat : public Animal { public: void meow() { cout << "Meow! 🐱" << endl; } }; int main() { Animal* a = new Cat(); Cat* c = dynamic_cast<Cat*>(a); if (c != nullptr) { c->meow(); } else { cout << "Not a Cat!" << endl; } delete a; return 0; }
🎯 Summary
- RTTI is useful for checking object types at runtime
- Use
typeid
to find the type name - Use
dynamic_cast
for safe downcasting in polymorphism