
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
RTTI - Run Time Type Information in C++
In this section, we will see what is the RTTI (Runtime Type Information) in C++. In C++ the RTTI is a mechanism, that exposes information about an object’s datatype during runtime. This feature can be available only when the class has at least one virtual function. It allows the type of an object to be determined when the program is executing.
In the following example, the first code will not work. It will generate an error like “cannot dynamic_cast base_ptr (of type Base*) to type ‘class Derived*’ (Source type is not polymorphic)”. This error comes because there is no virtual function in this example.
Example Code
#include<iostream> using namespace std; class Base { }; class Derived: public Base {}; int main() { Base *base_ptr = new Derived; Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr); if(derived_ptr != NULL) cout<<"It is working"; else cout<<"cannot cast Base* to Derived*"; return 0; }
Now after adding a virtual method, it will work.
Example Code
#include<iostream> using namespace std; class Base { virtual void function() { //empty function } }; class Derived: public Base {}; int main() { Base *base_ptr = new Derived; Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr); if(derived_ptr != NULL) cout<<"It is working"; else cout<<"cannot cast Base* to Derived*"; return 0; }
Output
It is working
Advertisements