Search code examples
c++design-patternspimpl-idiom

Pimpl with header containing the class


I came across an implementation which had the pimpl class as a header and included that in the pimpl implementation. Does it even make sense? Something like this:

UI.h

class UI {

public:

   UI();
   virtual ~UI();

   // bunch of methods
private:

      UIImpl* m_impl;
}

UIImpl.h

class UIImpl
{

public:

  UIImpl( ...) ;
  ......
}

UIImpl.cpp

#include "UIImpl.h" 

UIImpl::UIImpl()

{

  //Actual Implementation
  ...

}

I was thinking that the reason for PIMPL was to hide the implementation totally inside the cpp file. Does having a header defeat the purpose?


Solution

  • They're different kinds of header. UI.h is "public" - it's part of the external interface of the library, for use by its clients.

    UIImpl.h is "private," just as the UIImpl.cpp is. As long as it's never included in a public header, it can remain invisible to clients, just as the .cpp itself can.

    There can be several reasons for splitting the impl class definition into a header file. Perhaps some other implementation classes are passed UIImpl& parameters. Perhaps it's easier to run doxygen on headers only. Perhaps it's just project policy.

    The bottom line is, it's still Pimpl, as long as you don't publish the private header.