In most cases, when you write code in which you know the type of object you are working with, you simply use static_cast as it is more efficient.
Situations in which you need dynamic casting usually come (in my experience) due to a lack of forethought in design - usually where the developer fails to provide an enumeration or identifier that allows you to determine the type later in the code.
For example, I have already seen this situation in more than one project:
You can use a factory where internal logic decides which derived class the user wants, rather than the user explicitly choosing one. This factory, in an ideal world, returns an enumeration that will help you identify the type of returned object, but if it is not, you may need to check what type of object it gave you using dynamic_cast.
Your next question will obviously be this: why do you need to know the type of object that you use in your code using factory?
In an ideal world, you would not do this - the interface provided by the base class would be sufficient to manage all returned factory objects to all required extents. However, people do not create design. For example, if your factory creates abstract connection objects, you may suddenly realize that you need to access the UseSSL flag in your socket connection object, but the factory base does not support this and is not related to any of the other classes that use the interface. That way, maybe you can check if you want to use this type of derived class in your logic, and also set / set the flag directly if you are.
It is ugly, but it is not an ideal world, and sometimes you do not have time to reorganize an imperfect design completely in the real world under the pressure of work.
John Humphreys - w00te Aug 01 2018-12-12T00: 00Z
source share