Run Time Type Information(RTTI) in C++ (dynamic_cast and typeid also included)

Run time type information(RTTI)

In c++, we can find object types and even change the type of the object during the run-time of a program.

The process of finding object types and changing type of object during a run of a program is called RTTI.

To achieve RTTI in C++, we use dynamic_cast and typeid operators.

Condition for using dynamic_cast and typeid operators to achieve RTTI-:

To use dynamic_cast and typeid operators, base class should be of poymorphic type. i.e at least base class should have one virtual function.

Other uses of dynamic_cast operators-:

In C++, type of pointer object of derived class can be implicitly converted to type of pointer object of base class due to inheritance.

Meaning-: *derived can be converted to *base

BUT BUT, there is a problem in converting the pointer object of base class to pointer object of derived class.

So, for that reason dynamic_cast is used.

Condition for using dynamic_cast operator-:

In order to work for dynamic_cast operator, base class should be of polymorphic type.

typeid operator-:

In C++, objects types can be found during the run-time of a program by the help of a typeid operator.

Conditions required for the working of typeid operator-:

1)<typeinfo> header file should be included.

2)Base class should also be of polymorphic type i.e base class should have at least one pure virtual function.

eg-: Program to show the use of typeid operator in C++-:

Output-:

The types of i and j are the same

But the important use of typeid will occur during polymorphism (as said above)

Output-:

animal class pointing to object of type5human
animal class pointing to object of type3cow
animal class pointing to object of type6animal

Example program to show the use of dynamic_cast operator[or a program to show RTTI mechanism in C++ using dynamic_cast]-:

Output-:

animal class pointing to human class
human class
animal class pointing to cow class
cow class
animal class pointing to animal class
animal class
Q)Write a program to show RTTI using both dynamic_cast and typeid in C++.
To write this program, we will combine the above two programs in a single program.

Output-:

animal class pointing to object of type5human
animal class pointing to human class
human class
animal class pointing to object of type3cow
animal class pointing to cow class
cow class
animal class pointing to object of type6animal
animal class pointing to animal class
animal class

Leave a Comment

Your email address will not be published. Required fields are marked *

Do NOT follow this link or you will be banned from the site! Scroll to Top