Skip to content

Last updated:2026-10-12

C++ Pimpl Idiom

"Pointer to implementation", or "pImpl", is a C++ programming technique that removes the implementation details of a class from its object representation, puts them in a separate class, and accesses them through an opaque pointer.

The reasons for using the pImpl idiom are as follows:

Consider the following example:

class X
{
private:
  C c;
  D d;  
} ;

Turned into pImpl, it looks like this

class X
{
private:
  struct XImpl;
  XImpl* pImpl;       
};

The CPP definition:

struct X::XImpl
{
  C c;
  D d;
};
  • Binary compatibility

When developing a library, you can add/modify fields of XImpl without breaking binary compatibility with clients (doing so without pImpl would cause crashes!). Since the binary layout of class X does not change when new fields are added to the XImpl class, new functionality can safely be added to the library in a minor-version update.

Of course, you can also add new public/private non-virtual methods to X/XImpl without breaking binary compatibility, but that is on par with the standard header/implementation technique.

  • Data hiding

If you are developing a library, especially a proprietary one, you may not want to expose the other libraries/implementation techniques used to implement the library's public interface — whether because of intellectual-property concerns, or because you think users might be tempted to make dangerous assumptions about the implementation, or simply to break encapsulation with the aid of dreadful casting tricks. PIMPL solves/mitigates this problem.

  • Compilation time

Compilation time decreases, because when you add/remove fields and/or methods to/from the XImpl class (which only maps to adding private fields/methods under the standard technique), only X's source (implementation) file needs to be rebuilt. In practice, this is a common operation.

With the standard header/implementation technique (no PIMPL), when you add a new field to X, every client that used to allocate X (on the stack or on the heap) needs to be recompiled, because it must adjust the size of the allocation. Well, every client that never allocated X also needs to be recompiled, but that is just overhead (the resulting code on the client side is the same).

https://stackoverflow.com/questions/8972588/is-the-pimpl-idiom-really-used-in-practices

Comments