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_castconsidered 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?
This is EXACTLY the wrong place to use
dynamic_cast. You should be using polymorphism. Each of theAnimalclasses should have avirtualfunction, say,processand here you should just callanimal->process().Other problems.
What if
animalis aDog, but due to a buganimal_typesays its aCat?There are times when
static_castis necessary, and if possible use it instead ofdynamic_cast. Dynamic cast has the additional performance cost that static cast does not. For this, you need to be sure you know the type that is coming in, sincestatic_castis more unsafe.At the very least,
animal_typeshould be a member ofAnimal.