Saturday 17 December 2011

Using pimpl idiom C++


The Infamous pimpl idiom C++

Pimpl standing for Private Implementation is a famous C++ idiom  particularly popularized in Herb Sutter's Guru of the week column (www.gotw.ca).
It describes a way for hiding your class's private members,by making them invisible from your Header file. Remeber this fact that whenever compiler sees your class, it only sees the header file (.h) and not the implementation file (.cpp). So what this basically does is that it removes all your private members from your header file(.h) and adds them to your implementation file (.cpp). Additional advantage of this technique is that it makes your class immune to changes meaning that you dont need to recompile it again and again if you change the private memebers. Also it keeps you public interface clean, and the client programmer doesn't need to be aware of you private members. It achieves this by using an opaque pointer, which is a pointer to a forward declared class or structure.

Eg:
struct B_impl; //Forward declared structure
class A {
B-impl *my_Impl; //Opaque pointer
}

Here Structure B-impl is only forward declared so the pointer my_Impl is an opaque pointer.
Now lets jump directly into action and see how pimpl is implemented :

This is our class :
//file A.h
//So many header files increases compile time :(
#include<A.h>
#include<B.h>
#include<C.h>
#include<D.h>
#include<vector>


class A
{
B objB;
C objC;
vector vlist<D>;
}

Now lets implement pimp idiom --->
//file A.h
//What happened to all the header files.....??
strcut pimpl; //forward declared structure 
class A
{
pimpl *my_impl; //opaque pointer to implement pimpl
}


//file A.cpp
#include<A.h>


strcut pimpl
{
B objB;
C objC;
vector vlist<D>;
}

So this is how we implement pimpl :
1. forward declare some structure/class
2. Make a pointer of that strcutrure/class known as opaque pointer
3. Declare all the private members in the .cpp file inside the structure/class.

Now the big question is that what should go inside the pimpl strcuture/class....??
Remember some basic points in mind while designing pimpl idiom.
---> Take all your non-virtual private members (variables + functions)
---> Never take protected members, because they were made protected at the first place so that the derived class can see them, if you hide them then whats the point of making them protected in the first place...??
---> Make your pimpl structure/class exactly as your class A would have been and make your class A just as a plain easy to use public interface with forwarding functions.

But finally the question arrives "was the pimpl implementation worth the pain..."??
the question will always depend on the programmer who is implementing it. For what class he is implemeting it.

1 comment:

  1. Nice Explanation Ishkaran, It really helped me understanding the concept.
    Thanks.

    ReplyDelete