Search code examples
c++design-patternsimplementationforward-declarationinformation-hiding

Hiding implementation by forward declaration


I have a class, let's call it Product, the implementation of which I want to completely hide from the user. Nevertheless, I would like the user to collect the products, pass them around, generally, to decide what to do with them, without knowing what is inside.

The first idea that came to my mind was to simply create a ProductFactory class and forward declare Product class in the ProductFactory.h header.
The object of the Product class would be created by makeProduct method which would return a shared pointer to the Product class. The user would then not be able to see what is inside, but it could for example send it to the Service class, which in its implementation would include the full definition of Product so it could access its guts.
Do you think it is a good idea or feels rather like a workaround?

I was also thinking about using pimpl idiom, in case I needed some top-level functionality that the user could access, for example operator== so the user could check if the products are the same.

Please note, that the abstract base class is not an option, because there is not really an interface that would be both, limited enough for the user and sufficient for the Service class for example.


Solution

  • If the operations that shared_ptr gives you are sufficient for the user (e.g. there should be an operator==), then this solution should be a way to go.

    If you need more than this, then pimpl sounds like a good way, since you can define the operations the user needs inside your class and define the operations your Service class needs inside the impl. You can still use smart pointers here to make life easier.