[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppPimpl

(C++) pimpl

Short for 'pointer to implementation'. Using the pimple idion reduces compilation time. Pimpl judiciously [1].

Page overview:
  • The principle
  • A full example

The principle

The trick of the pimpl idiom is, that in the header file of a class a declaration of the implementation is mady using an opaque pointer ('a pointer to a declared, but undefined class'[2]). That is, all private functions will be in the implementation class:

class MyClass
{
  public:
  MyClass();
  void setX(const double&);
  double getX() const;
  private:
  class Impl; //Forward declaration (as Impl) is undefined
  Impl * pImpl; //Opaque pointer
};
//MyClass.cpp
  1. include "MyClass.h"
void Test::setX(const double& x) { pImpl->setX(x); } double Test::getX() const { return pImpl->getX(); }


As you see, everything 'really' happening goes on in the .cpp file. Now imaging that MyClass is a heavy used class. When you change the public part of it, all classes using it, need to be recompiled. The same is true if you change private functions, WHEN NOT using the pimpl idiom. When you do use the pimpl idiom, only the .cpp file is changed and this is the only one that needs to be recompiled!

A full example

A trivial example, but its a full one:

main.cpp:
  1. include <iostream>
  2. include "UnitPimpl.h"
int main(int argc, char* argv[]) { Test test; test.setX(123.456); std::cout << test.getX() << std::endl; return 0; }


UnitPimpl.h:
//Header guard (for those now knowing):
  1. ifndef UnitPimplH
  2. define UnitPimplH
  1. include <memory>
class Test { private: struct TestImpl; const std::auto_ptr<TestImpl> pImpl; public: Test(); ~Test() {}; void setX(const double& x); double getX() const; };
  1. endif


UnitPimpl.cpp:
  1. include "UnitPimpl.h"
struct Test::TestImpl { double x; }; Test::Test() : pImpl(new TestImpl) { //How RAII can you get? } void Test::setX(const double& x) { pImpl->x = x; } double Test::getX() const { return pImpl->x; }


Code links

References



last edited (November 16, 2006) by bilderbikkel, Number of views: 5659, Current Rev: 7 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.