🔎 C++ typeid – Discover the Real Type of an Object
The typeid keyword in C++ helps you check the real type of a variable while the program is running. It’s like saying, “Who are you really?” 🤔
This is especially useful when you’re working with pointers, references, and polymorphism.
🛠️ Syntax of typeid
typeid(expression).name()
It returns the type of the expression — the actual data type, not just the one you declared it as.
🔧 Example: Simple typeid usage
#include <iostream> #include <typeinfo> using namespace std; int main() { int a = 42; double b = 3.14; char c = 'A'; cout << "a is: " << typeid(a).name() << endl; cout << "b is: " << typeid(b).name() << endl; cout << "c is: " << typeid(c).name() << endl; return 0; }
🧬 Example with Polymorphism
Let’s see how typeid
reveals the actual object type when using base class pointers.
#include <iostream> #include <typeinfo> using namespace std; class Animal { public: virtual void speak() {} }; class Dog : public Animal {}; class Cat : public Animal {}; int main() { Animal* a = new Dog(); cout << "Actual type: " << typeid(*a).name() << endl; delete a; return 0; }
🎯 Remember
typeid
returns the real runtime type- Works best with pointers and polymorphism
- You must use
virtual
functions in the base class for accurate results