Quote:Original post by NumsgilQuote:Original post by the_edd
Limiting the use of dynamic_cast is the way it should be, you shouldn't be seeking to change that. An abundance of dynamic_casts (or any type of cast, really) points to design problems.
That depends. Should we avoid dynamic casts because they're slow,
Yes.
Quote:or because they lead to bad designs?
And double yes :)
Quote: A program in another language using dynamic typing is certainly valid if that's how the language is meant to be used.
These languages don't use dynamic casts. They simply use polymorphism. Perhaps the implementation of the language interpreter has type-switching or something functionally equivalent to a dynamic_cast internally, but this is hidden inside there because it's a bad idea to put it into user code.
For example in Python when I call a lambda or a function or an instance of a class that has a __call__ method, the interpreter doesn't dynamic_cast the object I'm calling to a function. It simply asks the object if it's callable.
Quote:Ruby for example. I haven't done much dynamic typing myself, but I recognize lots of strengths from it.
Dynamically typing is certainly nice for a lot of things, but it has nothing inherently to do with dynamic casts. It's just a higher level of polymorphism.
Quote:I would say you should avoid dynamic casts because they're slow, not because there's something inherently less flexible, or more risky, about a design incorporating them. Well, that and C++ is really built to be statically typed, and you're kind of twisting it to be dynamically typed. So you might code yourself in to a dead end with language limitations. But at its core I don't think there's anything evil about dynamic casting. Or I haven't seen any evidence of it anyway.
Well I would say, as your example shows, that you could redesign your hierarchy to avoid it i.e. you're not using the tools for polymorphism that the statically typed language provides, C++ in this case.
But as you point out, this isn't always easy and sometimes your program yourself in to a corner because runtime polymorphism in languages such as C++ is only really doable via inheritance. Since inheritance is a very strong form of coupling, this polymorphic behaviour is hard to change and you might end up having to do a dynamic_cast here or there. But this is the exception -- it's there because you've got yourself stuck. It's not a means to avoid getting stuck in the first place. Otherwise the syntax would be much nicer; the C++ cast syntax is designed to look ugly for a reason.