c++ - Why should the "PIMPL" idiom be used? -


this question has answer here:

backgrounder:

the pimpl idiom (pointer implementation) technique implementation hiding in public class wraps structure or class cannot seen outside library public class part of.

this hides internal implementation details , data user of library.

when implementing idiom why place public methods on pimpl class , not public class since public classes method implementations compiled library , user has header file?

to illustrate, code puts purr() implementation on impl class , wraps well.

why not implement purr directly on public class?

// 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(); ...     // actual implementation can };  cat::cat() {     cat_ = new catimpl; }  cat::~cat() {     delete cat_; }  cat::purr(){ cat_->purr(); } catimpl::purr(){    printf("purrrrrr"); } 

  • because want purr() able use private members of catimpl. cat::purr() not allowed such access without friend declaration.
  • because don't mix responsibilities: 1 class implements, 1 class forwards.

Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -