Sorry for not giving you a definitive and comprehensive answer. In my comments to the question, I tried why getting such answer right now won't be really helpful to you. First, you need to get a good idea on how OOP works. First of all, this is about understanding of the central point of OOP: late binding and polymorphism. If I tried to give you a single use case for dynamic cast, you would hardly understand it, due to its relative complexity.
But what answer would be just better than nothing? I strongly believe: the one which would provide you the hint for future. You probably won't understand it right now, but may appreciate after you not only grasp the central idea of OOP, but face with real problems of OOD.
So, as I say, in practice this is related to late binding and polymorphism and, hence, the mechanism if virtual functions. I mean, you can have dynamic_cast
working even without virtual functions, or have polymorphism without virtual functions, or perform dynamic_cast
without late binding and polymorphism, but it hardly may make any practical sense.
So, the quick answer is: people use dynamic_cast
when they fail to implement all the desired behavior following strict object-oriented approach. There are two major types of situations when it happens: 1) the whole design is a serious abuse of OOP; 2) the whole design reasonable uses OOP, but there is some detail which does not perfectly fit in this design, either it came up later and was not properly taken into account, or because it is inherently very different from all other design features; then this little detail is put into place by using dynamic_cast
as a small "hack".
The whole idea of the approach based on polymorphism is that you control all the detail of each elements of the polymorphic set exclusively based on the properties of the some class representing the interface common to all the elements. It could be a common base class, or, more generally, some "interface class" (in other object-oriented languages, there is a special construct "interface type" to express it) which is one of the base classes common to each and every elements of the polymorphic set of objects. In other words, all the operations should be type-agnostic. If this is not the case, you can get an object as an object of a concrete type instead; and this is where you use dynamic_cast
. You can get all further detail from the C++ documentation.
Sorry, no code samples and detailed descriptions of the concrete cases for you, not just yet. We can talk more after you grasp the central OOP conceptions quite well.
—SA
Updated 15-Nov-15 6:19am
v3