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


some the use of dynamic_cast means bad design , dynamic_cast can replaced virtual functions

  1. why use of dynamic_cast considered bad design?
  2. suppose have function name func(animal* animal, int animaltype) , implementation in func like:

    bool func(animal* animal, int animaltype) {   ...   /* animal base class of bear, panda, fish ....   dynamic_cast animal real animals(bear, panda, fish...)    according animaltype. processing specific   type of animal, using additional information beyond base    class animal. */ } 

is case proper use of dynamic_cast?

this wrong place use dynamic_cast. should using polymorphism. each of animal classes should have virtual function, say, process , here should call animal->process().

class animal{     virtual void process() = 0; } class cat:public animal{     void process() {cout<<" tiny cat";} } class bear :public animal{     void process(){cout<<"i big bear"; }  void func(animal* animal){     if(animal != null) animal -> process(); } 

other problems.

what animal dog, due bug animal_type says cat?

there times when static_cast necessary, , if possible use instead of dynamic cast. dynamic cast has additional performance cost static cast not. this, need sure know type coming in, since static_cast more unsafe.

p.s. @ least, animal_type should member of animal.


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -