Some say the use of dynamic_cast often means bad design and dynamic_cast can be replaced by virtual functions
- why is the use of
dynamic_cast
considered bad design? Suppose I have I function name
func(Animal* animal, int animalType)
, the implementation in func is like:bool func(Animal* animal, int animalType) { ... /* Animal is the base class of Bear, Panda, Fish .... dynamic_cast animal to real animals(Bear, Panda, Fish...) according to animalType. Do some processing with this specific type of animal, using its additional information beyond base class Animal. */ }
Is this case a proper use of dynamic_cast
?
dynamic_cast
is "evil" because it's slow/overkill. Aside from that, use the tool that solves your problem. End of story. – Alexiodynamic_cast
is "bad design" for the simple reason that it violates this purpose, since you need your object to be of some derived type, so it doesn't suffice to know the base type of it. That being said it still has its use (especially as the world isn't as simple as Java likes it to be). – Vlad