What confused me is that I don’t want to create a object with a pointer like ‘Product_ptr productA’, are there some other methods? Another questions is that all my products use DoSomething(), but I also want to add different attributes to different products, how to achieve this? Thanks for your suggestions!!
Share
Generally you cannot avoid pointers in C++ when dealing with dynamically created objects. You have to manage and pass ownership for such objects which is naturally done with pointers, mainly smart pointers, of course.
Despite there are some ways to hide them, e.g. maintaining ownership of objects in some central point (factory) and pass them to consumers by reference. Such way has several drawbacks, e.g. consumer need explicitly release the object so the factory can destroy it and not waste resources. But if your objects are lightweight and their lifetime is the same as lifetime fo entire program or specific factory, this could be useful.
Example:
This solution is possible, but has limitations, don’t use it without real need.
Returning appropriate smart pointer from factory, e.g.
std::shared_ptris preferable because it gives you explicit semantics on object ownership and makes code more clear, maintanable and error-proof.