The Private Implementation Design Pattern (PImpl) is a nice way to hide the internals of a class from other classes that would depend on it otherwise. The advantage of doing so is that it simplifies the header dependency tree which will result in faster build times. For larger systems and/or slow build servers, this may be very desirable. Let’s take a look at the pattern as implemented in C++. We will use our favorite object name Foo to be the class other classes would depend on. We want to limit those dependencies so we provide a private implementation of Foo called FooImpl, which Foo contains as a member. The attributes and behavior are encapsulated to the FooImpl class. You will see there are two data structures members in FooImpl. Without using the Private Implementation pattern, classes using Foo would have been dependent on the two header files for those data structures. Hope this helps anyone interested in the topic. Feedback is always appreciated! Code on!
In Foo.h
// Forward declare your private implementation class
// instead of including a header as that would defeat
// the point of the private implementation pattern
// of limiting header dependencies.
class FooImpl;
class Foo
{
public:
Foo();
~Foo();
void doSomething();
private:
FooImpl * m_pImpl;
}
In Foo.cc
#include "Foo.h"
#include "FooImpl.h"
Foo::Foo()
: m_pImpl(new FooImpl())
{
}
Foo::~Foo()
{
}
// delegate doing something to
// the private implementation object.
Foo::doSomething()
{
return m_pImpl->doSomething();
}
In FooImpl.h
#include "SomeDataStructure.h"
#include "SomeOtherDataStructure.h"
class FooImpl
{
public:
FooImpl();
~FooImpl();
void doSomething();
private:
SomeDataStructure m_someDataStructure;
SomeOtherDataStructure m_someOtherDataStructure;
};
In FooImpl.cc
#include "FooImpl.h"
FooImpl::FooImpl()
{
}
FooImpl::~FooImpl()
{
}
FooImpl::doSomething()
{
m_someDataStructure.doWork();
m_someOtherDataStructure.doWork();
}