C++ casting programmatically : can it be done?

后端 未结 8 442
你的背包
你的背包 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:54

    What are you trying to accomplish, exactly? In my experience, things like this are a sign of bad design. Re-evaluate your class hierarchy, because the goal of object oriented design is make things like this unnecessary.

    0 讨论(0)
  • 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();

    0 讨论(0)
提交回复
热议问题