How to use pimpl idiom to hide the internals of your class declaration (and not only)

When we share the public interface of our library or API, we usually share the header files. In this case together, with the public members od our class there is also visibility of the private. The pimpl idiom which comes from the “pointer to implementation” is a programming technique that let us hide the internal details of the headers, by moving the private members to the implementation file.

Let’s use an example to demonstrate how this technique works.

In this example, we can see that AutoTimer’s is completely minimal and the entire implementation is carried out by the TimerImpl. The latter is possible since pointers only need a forward declaration to compile.

In general, pimpl comes to hand not only for hiding the public members of your implementation but also to facilitate loose coupling and improve compile times.

Exceptional C++ by Herb Sutter
API Design for C++ by Martin Reddy
How to implement the pimpl idiom by using unique_ptr by Jonathan Boccara Blog