<p>Backgrounder:</p>

<p>The <a href="http://en.wikipedia.org/wiki/Opaque_pointer" rel="noreferrer">PIMPL Idiom</a> (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.</p>

<p>This hides internal implementation details and data from the user of the library.</p>

<p>When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?</p>

<p>To illustrate, this code puts the <code>Purr()</code> implementation on the impl class and wraps it as well.</p>

<p><strong>Why not implement Purr directly on the public class?</strong></p>

<pre class="lang-c++ prettyprint-override"><code>// header file:
class Cat {
    private:
        class CatImpl;  // Not defined here
        CatImpl *cat_;  // Handle

    public:
        Cat();            // Constructor
        ~Cat();           // Destructor
        // Other operations...
        Purr();
};


// CPP file:
#include "cat.h"

class Cat::CatImpl {
    Purr();
...     // The actual implementation can be anything
};

Cat::Cat() {
    cat_ = new CatImpl;
}

Cat::~Cat() {
    delete cat_;
}

Cat::Purr(){ cat_-&gt;Purr(); }
CatImpl::Purr(){
   printf("purrrrrr");
}
</code></pre>

[{'answer_id': 60575, 'author': 'Phil Wright', 'author_id': 6276, 'author_profile': 'https://Stackoverflow.com/users/6276', 'pm_score': 2, 'selected': False, 'text': '<p>Placing the call to the impl-&gt;Purr inside the .cpp file means that in the future you could do something completely different without having to change the header file.</p>\n<p>Maybe next year they discover a helper method they could have called instead and so they can change the code to call that directly and not use impl-&gt;Purr at all. (Yes, they could achieve the same thing by updating the actual impl::Purr method as well, but in that case you are stuck with an extra function call that achieves nothing but calling the next function in turn.)</p>\n<p>It also means the header only has definitions and does not have any implementation which makes for a cleaner separation, which is the whole point of the idiom.</p>\n'}, {'answer_id': 60579, 'author': 'Rob Wells', 'author_id': 2974, 'author_profile': 'https://Stackoverflow.com/users/2974', 'pm_score': 6, 'selected': False, 'text': '<p>I think most people refer to this as the <em>Handle Body</em> idiom. See James Coplien\'s book <em><a href="https://rads.stackoverflow.com/amzn/click/com/0201548550" rel="noreferrer" rel="nofollow noreferrer">Advanced C++ Programming Styles and Idioms</a></em>. It\'s also known as the <a href="http://en.wikipedia.org/wiki/Cheshire_Cat" rel="noreferrer">Cheshire Cat</a> because of <a href="https://en.wikipedia.org/wiki/Lewis_Carroll" rel="noreferrer">Lewis Caroll\'s</a> character that fades away until only the grin remains.</p>\n<p>The example code should be distributed across two sets of source files. Then only <em>Cat.h</em> is the file that is shipped with the product.</p>\n<p><em>CatImpl.h</em> is included by <em>Cat.cpp</em> and <em>CatImpl.cpp</em> contains the implementation for <em>CatImpl::Purr()</em>. This won\'t be visible to the public using your product.</p>\n<p>Basically the idea is to hide as much as possible of the implementation from prying eyes.</p>\n<p>This is most useful where you have a commercial product that is shipped as a series of libraries that are accessed via an API that the customer\'s code is compiled against and linked to.</p>\n<p>We did this with the rewrite of <a href="https://en.wikipedia.org/wiki/IONA_Technologies" rel="noreferrer">IONA\'s</a> <a href="https://en.wikipedia.org/wiki/Orbix_(software)" rel="noreferrer">Orbix</a> 3.3 product in 2000.</p>\n<p>As mentioned by others, using his technique completely decouples the implementation from the interface of the object. Then you won\'t have to recompile everything that uses <em>Cat</em> if you just want to change the implementation of <em>Purr()</em>.</p>\n<p>This technique is used in a methodology called <a href="http://en.wikipedia.org/wiki/Design_by_contract" rel="noreferrer">design by contract</a>.</p>\n'}, {'answer_id': 60582, 'author': 'Wilka', 'author_id': 1367, 'author_profile': 'https://Stackoverflow.com/users/1367', 'pm_score': 3, 'selected': False, 'text': "<p>Typically, the only reference to a PIMPL class in the header for the <em>owner</em> class (<em>Cat</em> in this case) would be a forward declaration, as you have done here, because that can greatly reduce the dependencies.</p>\n<p>For example, if your PIMPL class has <em>ComplicatedClass</em> as a member (and not just a pointer or reference to it) then you would need to have <em>ComplicatedClass</em> fully defined before its use. In practice, this means including file &quot;ComplicatedClass.h&quot; (which will also indirectly include anything <em>ComplicatedClass</em> depends on). This can lead to a single header fill pulling in lots and lots of stuff, which is bad for managing your dependencies (and your compile times).</p>\n<p>When you use the PIMPL idiom, you only need to #include the stuff used in the public interface of your <em>owner</em> type (which would be <em>Cat</em> here). Which makes things better for people using your library, and means you don't need to worry about people depending on some internal part of your library - either by mistake, or because they want to do something you don't allow, so they #define private public before including your files.</p>\n<p>If it's a simple class, there's usually isn't any reason to use a PIMPL, but for times when the types are quite big, it can be a big help (especially in avoiding long build times).</p>\n"}, {'answer_id': 60605, 'author': 'Xavier Nodet', 'author_id': 4177, 'author_profile': 'https://Stackoverflow.com/users/4177', 'pm_score': 6, 'selected': True, 'text': "<ul>\n<li>Because you want <code>Purr()</code> to be able to use private members of <code>CatImpl</code>.  <code>Cat::Purr()</code> would not be allowed such an access without a <code>friend</code> declaration.</li>\n<li>Because you then don't mix responsibilities: one class implements, one class forwards.   </li>\n</ul>\n"}, {'answer_id': 60616, 'author': 'Nick', 'author_id': 4949, 'author_profile': 'https://Stackoverflow.com/users/4949', 'pm_score': 4, 'selected': False, 'text': "<p>If your class uses the PIMPL idiom, you can avoid changing the header file on the public class.</p>\n<p>This allows you to add/remove methods to the PIMPL class, without modifying the external class's header file. You can also add/remove #includes to the PIMPL too.</p>\n<p>When you change the external class's header file, you have to recompile everything that #includes it (and if any of those are header files, you have to recompile everything that #includes them, and so on).</p>\n"}, {'answer_id': 60618, 'author': 'JeffV', 'author_id': 445087, 'author_profile': 'https://Stackoverflow.com/users/445087', 'pm_score': 0, 'selected': False, 'text': '<p>I don\'t know if this is a difference worth mentioning but...</p>\n\n<p>Would it be possible to have the implementation in its own namespace and have a public wrapper / library namespace for the code the user sees:</p>\n\n<pre><code>catlib::Cat::Purr(){ cat_-&gt;Purr(); }\ncat::Cat::Purr(){\n   printf("purrrrrr");\n}\n</code></pre>\n\n<p>This way all library code can make use of the cat namespace and as the need to expose a class to the user arises a wrapper could be created in the catlib namespace.</p>\n'}, {'answer_id': 62059, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 0, 'selected': False, 'text': "<p>I find it telling that, in spite of how well-known the PIMPL idiom is, I don't see it crop up very often in real life (e.g., in open source projects).</p>\n<p>I often wonder if the &quot;benefits&quot; are overblown; yes, you can make some of your implementation details even more hidden, and yes, you can change your implementation without changing the header, but it's not obvious that these are big advantages in reality.</p>\n<p>That is to say, it's not clear that there's any need for your implementation to be <em>that</em> well hidden, and perhaps it's quite rare that people really do change only the implementation; as soon as you need to add new methods, say, you need to change the header anyway.</p>\n"}, {'answer_id': 678205, 'author': 'markh44', 'author_id': 79047, 'author_profile': 'https://Stackoverflow.com/users/79047', 'pm_score': 1, 'selected': False, 'text': '<p>I just implemented my first PIMPL class over the last couple of days. I used it to eliminate problems I was having, including file *winsock2.*h in Borland Builder.  It seemed to be screwing up struct alignment and since I had socket things in the class private data, those problems were spreading to any .cpp file that included the header.</p>\n<p>By using PIMPL, <em>winsock2.h</em> was included in only one .cpp file where I could put a lid on the problem and not worry that it would come back to bite me.</p>\n<p>To answer the original question, the advantage I found in forwarding the calls to the PIMPL class was that the PIMPL class is the same as what your original class would have been before you pimpl\'d it, plus your implementations aren\'t spread over two classes in some weird fashion. It\'s much clearer to implement the public members to simply forward to the PIMPL class.</p>\n<p>Like <a href="https://stackoverflow.com/questions/60570/why-should-the-pimpl-idiom-be-used/60605#60605">Mr Nodet said</a>, one class, one responsibility.</p>\n'}, {'answer_id': 6426059, 'author': 'Esben Nielsen', 'author_id': 808531, 'author_profile': 'https://Stackoverflow.com/users/808531', 'pm_score': 2, 'selected': False, 'text': "<p>Well, I wouldn't use it. I have a better alternative:</p>\n<h3>File <em>foo.h</em></h3>\n<pre><code>class Foo {\npublic:\n    virtual ~Foo() { }\n    virtual void someMethod() = 0;\n\n    // This &quot;replaces&quot; the constructor\n    static Foo *create();\n}\n</code></pre>\n<h3>File <em>foo.cpp</em></h3>\n<pre><code>namespace {\n    class FooImpl: virtual public Foo {\n\n    public:\n        void someMethod() {\n            //....\n        }\n    };\n}\n\nFoo *Foo::create() {\n    return new FooImpl;\n}\n</code></pre>\n<p>Does this pattern have a name?</p>\n<p>As someone who is also a Python and Java programmer, I like this a lot more than the PIMPL idiom.</p>\n"}, {'answer_id': 25993728, 'author': 'the swine', 'author_id': 1140976, 'author_profile': 'https://Stackoverflow.com/users/1140976', 'pm_score': 5, 'selected': False, 'text': '<p>For what is worth, it separates the implementation from the interface. This is usually not very important in small size projects. But, in large projects and libraries, it can be used to reduce the build times significantly.</p>\n<p>Consider that the implementation of <code>Cat</code> may include many headers, may involve template meta-programming which takes time to compile on its own. Why should a user, who just wants to use the <code>Cat</code> have to include all that? Hence, all the necessary files are hidden using the pimpl idiom (hence the forward declaration of <code>CatImpl</code>), and using the interface does not force the user to include them.</p>\n<p>I\'m developing a library for nonlinear optimization (read &quot;lots of nasty math&quot;), which is implemented in templates, so most of the code is in headers. It takes about five minutes to compile (on a decent multi-core CPU), and just parsing the headers in an otherwise empty <code>.cpp</code> takes about a minute. So anyone using the library has to wait a couple of minutes every time they compile their code, which makes the development quite <a href="http://xkcd.com/303/" rel="nofollow noreferrer">tedious</a>. However, by hiding the implementation and the headers, one just includes a simple interface file, which compiles instantly.</p>\n<p>It does not necessarily have anything to do with protecting the implementation from being copied by other companies - which wouldn\'t probably happen anyway, unless the inner workings of your algorithm can be guessed from the definitions of the member variables (if so, it is probably not very complicated and not worth protecting in the first place).</p>\n'}, {'answer_id': 26871719, 'author': 'nurettin', 'author_id': 227755, 'author_profile': 'https://Stackoverflow.com/users/227755', 'pm_score': 2, 'selected': False, 'text': '<p>We use the PIMPL idiom in order to emulate <a href="https://en.wikipedia.org/wiki/Aspect-oriented_programming" rel="nofollow noreferrer">aspect-oriented programming</a> where pre, post and error aspects are called before and after the execution of a member function.</p>\n<pre><code>struct Omg{\n   void purr(){ cout&lt;&lt; &quot;purr\\n&quot;; }\n};\n\nstruct Lol{\n  Omg* omg;\n  /*...*/\n  void purr(){ try{ pre(); omg-&gt; purr(); post(); }catch(...){ error(); } }\n};\n</code></pre>\n<p>We also use a pointer-to-base class to share different aspects between many classes.</p>\n<p>The drawback of this approach is that the library user has to take into account all the aspects that are going to be executed, but only sees his/her class. It requires browsing the documentation for any side effects.</p>\n'}]
['https://Stackoverflow.com/questions/60570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445087/']