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

前端 未结 3 1656
小鲜肉
小鲜肉 2021-01-12 06:20

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 consi
3条回答
  •  Happy的楠姐
    2021-01-12 06:51

    In theory, down-casting should never be necessary. Instead you should adapt the base class to include the necessary virtual method.

    In practice, you encounter things such as 3rd party libraries. In this case, modifying the base class is not an option and thus you may be forced into using dynamic_cast...

    Back to your example:

    class Animal {
    public:
        // starts moving toward `p`,
        // throws a `Unreachable` exception if `p` cannot be reached at the moment.
        virtual void moveToward(Point const& p) = 0;
    }; // class Animal
    

    And then:

    bool move(Animal& animal, Point const& p) {
        try {
            animal.moveToward(p);
            return true;
        } catch (Unreachable const& e) {
            LOG(animal.id() << " cannot reach " << p << ": " << e.what());
        }
    
        return false;
    } // move
    

提交回复
热议问题