I once asked a question about how to design a piece of C++ code (which can be found here C++ - Good or bad practice?) and people told me that down-casting is considered a bad practice except for very specific scenarios.
However, I've seen many pieces of code in C# and Java where it seems to be a totally natural way of doing things. For example in Android SDK, you have the function Activity#findViewById()
that returns a View that you then down cast to its actual class:
TextView tv = (TextView) this.findViewById( R.id.myTextView );
Why would this need to be avoided in C++ and not in other languages ?
I know that C# and Java both support introspection natively, and not C++ which would require on kind of type field, but in the end it's the same thing, isn't it ?
There are at least a couple of very different reasons, all of which are important:
Conceptual: Other languages (especially Java, but to a large extent also C# and similar languages that strongly encourage the use of "reference types") use run-time polymorphism as a single tool to solve a lot of different problems (compile-time polymorphism, code reuse, performance enhancement, type erasure, run-time polymorphism, etc.), whereas C++ has different, more specialized and more appropriate solutions to the individual problems. (Templates, value types, and the like can be used to solve the individual problems.) Consequently, polymorphism in C++ is much less common in other languages, and in the remaining cases where it is common, it is often (but not always) inappropriate to use the equivalent of downcasts or instanceof
.
Pragmatic: The downcasting operator in C++ is fundamentally extraordinarily slow compared to the performance of other operators, in main part due to the fact that C++ allows multiple- and virtual-inheritance. Other languages don't, so their casts are much simpler. Moreover, certain compilers' implementations themselves have historically had even slower implementations of downcasting (e.g. I believe 64-bit Visual C++ was one of them). Consequently, developers try to avoid it at all costs due to its practical performance characteristics, on top of the conceptual reasons (#1).
Because of these reasons, it's really a bad idea to use dynamic_cast
in C++ unless you absolutely need to.