C++ in theory: Bridging Your Classes with PIMPLs - The Private Implementation
(Page 2 of 4 )
The private implementation is a variation of the Bridge Pattern [Gamma], which is intended to decouple an abstraction from its implementation, so that the two can vary independently.
When you take a look at the C++ header and class declaration, you will notice that both the public and private interface is usually declared at the same location. Conceptually this is quite strange: in effect, the class lets you peek at its private parts, which should be of no concern to you. So let's hide it!
// MyClass.h
class MyClassImpl; // forward declaration
class MyClass {
public:
MyClass();
~MyClass();
int foo();
private:
MyClassImpl *m_pImpl;
};
The only visible private member variable in our class is the pimpl. We defined a forward declaration of the private implementation class; we don’t need any further information about it. The compiler needs to know how much memory to reserve for MyClass. Since we are only storing a pointer (which on my win32 platform is 4 bytes big), the compiler doesn’t care what the memory layout of MyClassImpl looks like.
Unless you make changes to the public interface, this header file is unlikely to change! Lets take a look at the implementation.
// MyClass.cpp
class MyClassImpl {
public:
int foo() {
var*=var;
return bar();
}
int bar() { return var & 0xFF; }
int var;
};
MyClass::MyClass()
: m_pImpl(new MyClassImpl)
{}
MyClass::~MyClass()
{
try { delete m_pImpl; }
catch (...) {}
}
int MyClass::foo()
{ return m_pImpl->foo(); }
The implementation class is defined in our source file, literally confined to the source implementation of our class. Any changes to our implementation class (the introduction of new member variables and member functions, for example) will trigger no recompilations outside this source file.
Basically all public functions redirect the call to the function in the private implementation when you implement a pimpl, although this is not strictly necessary. MyClass::foo() could also be implemented as:
int MyClass::foo() {
m_pImpl->var*=m_pImpl->var;
return m_pImpl->bar();
}
I consider it to be more effective and cleaner to just redirect the call to the pimpl. It also saves you multiple pointer dereferences.
The destruction of the pimpl is wrapped in a try-catch block, because we don’t want any exceptions to escape our own destructor. We do this because, when MyClass is destroyed by the exception-handling mechanism during the stack-unwinding part of exception propagation, any exceptions triggered during this destruction will force C++ to call the terminate function [Meyers]. Immediate termination of your application is one of the worst things that can happen to it!
Next: Pimpl Drawbacks >>
More C++ Articles
More By J. Nakamura