When to use RTTI – Dynamic_cast in C++

(Last Updated On: November 5, 2016)

When to use RTTI (Run Time Type Information) dynamic_cast in C++ is frequently asked c++ technical interview question. Answer to this question will cover multiple scenarios where we can use dynamic_cast in C++ program.

Answer:

Scenarios – Use of Dynamic_cast in C++ program:

Situation 1- When we need to call a specialized member function of child class that’s not available to the base class in inheritance hierarchy. Polymorphism breaks down here but sometimes we get this situation.  Below, class B contains specialized funcB() function.

 

 

What if we need to call specialized funcB() using base class pointer like below program. Dynamic cast operator, Part of RTTI in C++ comes into picture to type cast from base to child class.

 

 

Situation 2 – We want to override a function from base class that is not virtual and we can’t make it virtual as base class is sitting in a library and it can’t be modified.

So, overriding is not possible. If we use statements for below program, A* ptr = new B(), ptr->func2(); always base call method will be called as its not virtual in base class. But we want to call child class func2() method.

Then we need to use dynamic_cast operator to type cast base pointer to child pointer to call child’s class method.

 

 

Complete Example: Situation-1: Call specialized member function of a child class using dynamic_cast RTTI in C++.

 

 

Complete Example: Situation-2: Call child class method if it is not virtual in base class in C++