RTTI (Run-time type Information) in C++
In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object’s data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution
For example, dynamic_cast uses RTTI and following program fails with error “cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type is not polymorphic) ” because there is no virtual function in the base class B.
// CPP program to illustrate // Run Time Type Identification #include<iostream> using namespace std; class B { }; class D: public B {}; int main() { B *b = new D; D *d = dynamic_cast<D*>(b); if(d != NULL) cout<<"works"; else cout<<"cannot cast B* to D*"; getchar(); return 0; } |
chevron_right
filter_none
Adding a virtual function to the base class B makes it working.
// CPP program to illustrate // Run Time Type Identification #include<iostream> using namespace std; class B { virtual void fun() {} }; class D: public B { }; int main() { B *b = new D; D *d = dynamic_cast<D*>(b); if(d != NULL) cout << "works"; else cout << "cannot cast B* to D*"; getchar(); return 0; } |
chevron_right
filter_none
Output:
works
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Data type of character constants in C and C++
- Can a C++ class have an object of self type?
- Type difference of character literals in C and C++
- Function overloading and return type
- Type of 'this' pointer in C++
- Catch block and type conversion in C++
- const_cast in C++ | Type Casting operators
- Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction)
- Type Inference in C++ (auto and decltype)
- Data Type Ranges and their macros in C++
- Conversion of Struct data type to Hex String and vice versa
- Array Type Manipulation in C++
- Bool data type in C++
- Comparison of boolean data type in C++ and Java
- C++ set for user define data type



