Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

windows - Convert from a Base object to a Derived object in C++

I am trying to abstract sections of code to be platform independent.

I have one section of code that is creating objects of Base class IModel.

std::shared_ptr<IModel> joint_model_3d = std::make_shared<IModel>();

I have another section of code that is responsible for rendering. In order to render the object I need to convert it to the derived class Direct3DModel

class Direct3DModel : public IModel

I know that I can do a dynamic_cast from Direct3DModel to IModel for sections of code that are platform independent, and then dynamic_cast back into Direct3DModel for rendering.

My question is, can I create an object of the Base class IModel in the platform independent code, which is not supposed to know Direct3DModel, and convert it to Direct3DModel when I need it for rendering.

Would I need some kind of object creator class that is not platform independent for this?

question from:https://stackoverflow.com/questions/65852204/convert-from-a-base-object-to-a-derived-object-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My question is, can I create an object of the Base class IModel in the platform independent code, which is not supposed to know Direct3DModel, and convert it to Direct3DModel when I need it for rendering.

No, that won't work.

You'll have to create a Direct3DModel object in the code base that knows about the class. The platform independent code needs to call the platform dependent code to construct such an object. You may use the Factory Pattern to implement the functionality.

The platform independent code will have to work with base class pointers and references (IModel in your case). As long as the pointer/reference points to a Direct3DModel object, you may use dynamic_cast in the platform-specific code to get a pointer/reference to the Direct3DModel to proceed with the platform-specific logic.

Would I need some kind of object creator class that is not platform independent for this?

Yes. The Factory Pattern facilitates that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...