Alex Rivera | Logout

What is this design pattern? How to use it?

Asked 2012-01-31T20:26:16.873
11

Suppose I have class like this (simplified):

class Foo_p;
class Foo
{
private:
  Foo_p *p;
public:
  Foo();
  /* methods, etc... */
};

This class is a part of an API. The Foo_p is all the private parts of the class, which are not declared in the class Foo itself as usual, but rather in a separate forward-declared class that is only used by the underlying implementation not visible on the outside.

I've seen this pattern used in a couple of projects, is there a name for it?

Also, how do I use it properly (e.g. exception safety, etc.)? Where should the actual implementation go? In class Foo, as usual, only using Foo_p for storage of data, or in the Foo_p class with Foo being just a wrapper?

Edit
Report

1 Answer

8

This is known is PIMPL. private/pointer-to-private implementation. The class, Foo_p, your class would have been is implemented privately and accessed through a pointer to it so that rather than displaying the true class to clients, they only get to see the public interface you chose to expose. It essentially abstracts away from the header the vestiges of implementation detail present in the protected and private members.

I've found it unwieldy in VC++- it breaks code completion. It is useful if you are very sure of your implementation and don't want the private and protected members on display in the header.

I put the actual implementation of class Foo_p in the cpp file for class Foo, although this may have been the cause of the code-completion breaking, at least I don't have to run the risk of the class being reused by inclusion of its header.

answered 2012-01-31T20:29:29.620

Your Answer