Why is dynamic_cast evil or not ? Should I use dynamic_cast in this case?

Gary Gauh picture Gary Gauh · Aug 26, 2013 · Viewed 7.9k times · Source

Some say the use of dynamic_cast often means bad design and dynamic_cast can be replaced by virtual functions

  1. why is the use of dynamic_cast considered bad design?
  2. 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?

Answer

Karthik T picture Karthik T · Aug 26, 2013

This is EXACTLY the wrong place to use dynamic_cast. You should be using polymorphism. Each of the Animal classes should have a virtual function, say, process and here you should just call animal->process().

class Animal {
    virtual void Process() = 0;
}

class Cat : public Animal {
    void Process() { std::cout << " I am a tiny cat"; }
}

class Bear : public Animal {
    void Process() { std::cout << "I am a big bear"; }
}

void func(Animal * animal) {
    if (animal != nullptr) { animal->Process(); }
}

Other problems.

What if animal is a Dog, but due to a bug animal_type says its a Cat?

There are times when static_cast is necessary, and if possible use it instead of dynamic_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, since static_cast is more unsafe.

At the very least, animal_type should be a member of Animal.