C++ typeid Keyword
The typeid keyword in C++ is used to get information about the type of a variable, object, or expression at runtime. It is part of the typeinfo header and is commonly used for runtime type identification (RTTI). The typeid operator returns a reference to a type_info object, which can provide details like the type’s name.
The typeid keyword is used in polymorphic scenarios where you need to determine the actual type of an object at runtime.
Syntax
</>
Copy
typeid(expression).name()
- typeid
- The operator used to obtain runtime type information.
- expression
- The variable, object, or expression whose type information is required.
- name()
- A member function of the
type_infoobject that returns the name of the type as a string.
Examples
Example 1: Getting the Type of a Variable
This example demonstrates how to use typeid to get the type of a variable.
</>
Copy
#include <iostream>
#include <typeinfo> // Required for typeid
using namespace std;
int main() {
int num = 42;
float pi = 3.14;
char letter = 'A';
cout << "Type of num: " << typeid(num).name() << endl;
cout << "Type of pi: " << typeid(pi).name() << endl;
cout << "Type of letter: " << typeid(letter).name() << endl;
return 0;
}
Output:
Type of num: i
Type of pi: f
Type of letter: c
Explanation:
- The
typeidoperator is used with the variablesnum,pi, andletterto determine their types. - The
name()function of thetype_infoobject returns the names of their respective types:int,float, andchar. - The output shows the type names for each variable.
Example 2: Using typeid with Polymorphism
This example demonstrates how typeid can be used in a polymorphic scenario to identify the actual type of an object at runtime.
</>
Copy
#include <iostream>
#include <typeinfo>
using namespace std;
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {};
int main() {
Base* basePtr = new Derived();
cout << "Type of basePtr: " << typeid(basePtr).name() << endl;
cout << "Type of *basePtr: " << typeid(*basePtr).name() << endl;
delete basePtr;
return 0;
}
Output:
Type of basePtr: P4Base
Type of *basePtr: 7Derived
Explanation:
- The class
Basehas a virtual destructor, enabling runtime type identification. - The pointer
basePtrpoints to an object of the derived classDerived. typeid(basePtr)returns the type of the pointer, which isBase*.typeid(*basePtr)dereferences the pointer and returns the type of the actual object it points to, which isDerived.
Key Points to Remember about typeid Keyword
- The
typeidoperator is used to retrieve the type information of variables, objects, or expressions. - It works with polymorphic types when the base class has at least one virtual function.
- The
typeidoperator returns atype_infoobject, which provides aname()function to get the type’s name. - It is commonly used for debugging, logging, and implementing runtime type identification (RTTI).
- To use
typeid, include the<typeinfo>header.
