RTTI
RTTI - run time type identification is a concept in C++, which gives us the type of the object during run time. It can be used for safe cast using dynamic_cast<> operator.
In the original C++ design, Bjarne Stroustrup did not include RTTI, thinking it was often misused.
RTTI can be used only with polymorphic classes - i.e. the classes which have at least one virtual function.
Typeid
typeid is an operator in C++ which gives the actual type of the object. It returns a reference to type_info object.
So what is actual type of object? Is it different from the one we have defined it with?
It may be.
In the code above, type of a is integer. Type of obj1 is A. Type of obj2 is B.
But what about *ptr1? Is the type of *ptr1 A or B?
typeid operator correctly gives its type as B.
Note : We have added a dummy virtual print function in base class, to make A as polymorphic.
Now let us use typeid operator - which needs the inclusion of header file typeinfo
Output of the program is
Type of a is i
Type of obj1 is 1A
Type of *ptr1 is 1B
What is this output? What do i, 1A, 1B mean?
gcc compiler gives mangled names with typeid operator. To get the unmangled names we can pipe the output of the program to c++filt -t.
./a.out |c++filt -t
Type of v1 is int
Type of obj1 is A
Type of *ptr1 is B
Next let us see how to use dynamic_cast
Dynamic cast
dynamic_cast is used for safe conversion of variables. It can be used for upcast or even downcast objects. If we use correct type for dynamic_cast, we get the required value. If not, the program aborts with type error.
In this program in printDyn() function, we are converting the reference parameter of A to reference to C class. In the first call printDyn(objc), the code works fine because, objc is a C type object.
But when we call the function with object of B class and try to convert it into C reference, the program gives a bad_cast exception and aborts.
Output of the program will be
./a.out
We are in printDyn function
we call print functionprint function of class A
We are in printDyn function
terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast
Aborted
Also remember that target of dynamic_cast must be either a pointer or a reference to a class.