c++ - Why should the "PIMPL" idiom be used? -
this question has answer here:
- is pimpl idiom used in practice? 11 answers
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 ofcatimpl
.cat::purr()
not allowed such access withoutfriend
declaration. - because don't mix responsibilities: 1 class implements, 1 class forwards.
Comments
Post a Comment