
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- RTTI (Run-time type Information) in C++ program
- What is run time polymorphism in C#?
- Explain Compile time and Run time initialization in C programming?
- Using run-time polymorphism in Java
- Run-time Stack mechanism in Java
- C Program on two-dimensional array initialized at run time
- Are Generics applied at compile time or run time?
- What is Java run time environment?
- Get current time information in Java
- What is the difference between compile time errors and run time errors in Java?
- How to request Location permission at run time in Android?
- How to check grant permission at run-time in android?
- What are Java JVM Run-time Data Areas?
- How to Run a Command with Time Limit (Timeout) In Linux
- What is role of Run-time Storage Management in compiler design?

Advertisements