C++ casting programmatically : can it be done?

后端 未结 8 443
你的背包
你的背包 2021-01-13 06:18

Let\'s say I have a Base class and several Derived classes. Is there any way to cast an object to one of the derived classes without the ne

8条回答
  •  鱼传尺愫
    2021-01-13 06:56

    I think dynamic_cast is the way to go, but I don't particularly think this is a bad design for all possible conditions because object to be casted may be something provided by some third-party module. Let's say object was created by a plug-in that the application author has no knowledge of. And that particular plug-in may create Derived1 (being the old version) type object or Derived2 (being the new version) type object. Maybe the plug-in interface was not designed to do version specific stuff, it just creates the object so the application must do this kind of checking to ensure proper casting/execution. After this, we can safely call object.doSomethingUsefulThatDoesNotExistInDerived1();

提交回复
热议问题