Should pointers be used to reduce header dependencies? - c++

When creating a class that is composed of other classes, is it worthwhile reducing dependencies (and hence compile times) by using pointers rather than values?
For example, the below uses values.
// ThingId.hpp
class ThingId
{
// ...
};
// Thing.hpp
#include "ThingId.hpp"
class Thing
{
public:
Thing(const ThingId& thingId);
private:
ThingId thingId_;
};
// Thing.cpp
#include "Thing.hpp"
Thing::Thing(const ThingId& thingId) :
thingId_(thingId) {}
However, the modified version below uses pointers.
// ThingId.hpp
class ThingId
{
// ...
};
// Thing.hpp
class ThingId;
class Thing
{
public:
Thing(const ThingId& thingId);
private:
ThingId* thingId_;
};
// Thing.cpp
#include "ThingId.hpp"
#include "Thing.hpp"
Thing::Thing(const ThingId& thingId) :
thingId_(new ThingId(thingId)) {}
I've read a post that recommends such an approach, but if you have a large number of pointers, there'll be a large number of new calls, which I imagine would be slow.

This is what most people call the Pimpl idiom (http://c2.com/cgi/wiki?PimplIdiom).
Simple Answer
I highly suspect that you do not have a good use case for this and should avoid it at all cost.
My Experience
The main way that Pimpl has ever been useful for me is to make an implementation detail private. It achieves this because you do not need to include the headers of your dependencies, but can simply forward declare their types.
Example
If you want to provide an SDK to someone which uses some boost library code under the hood, but you want the option of later swapping that out for some other library without causing any problem for the consumer of your SDK, then Pimpl can make a lot of sense.
It also helps create a facade over an implementation so that you have control over the entire exposed public interface, rather than exposing the library you implicitly depend on, and consequently its entire interface that you don't have control over and may change, may expose too much, may be hard to use, etc.

If your program doesn't warrant dynamic allocation, don't introduce it just for the sake of project organisation. That would definitely be a false economy.
What you really want to do is attempt to reduce the number of inter-class dependencies entirely.
However, as long as your coupling is sensible and tree-like, don't worry too much about it. If you're using precompiled headers (and you are, right?) then none of this really matters for compilation times.

Related

Is forward declaring a class a correct way to hide the implementation? [duplicate]

This question already has answers here:
Is the PIMPL idiom really used in practice?
(12 answers)
Closed 8 years ago.
Backgrounder:
The PIMPL Idiom (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.
This hides internal implementation details and data from the user of the library.
When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?
To illustrate, this code puts the Purr() implementation on the impl class and wraps it as well.
Why not implement Purr directly on the public class?
// header file:
class Cat {
private:
class CatImpl; // Not defined here
CatImpl *cat_; // Handle
public:
Cat(); // Constructor
~Cat(); // Destructor
// Other operations...
Purr();
};
// CPP file:
#include "cat.h"
class Cat::CatImpl {
Purr();
... // The actual implementation can be anything
};
Cat::Cat() {
cat_ = new CatImpl;
}
Cat::~Cat() {
delete cat_;
}
Cat::Purr(){ cat_->Purr(); }
CatImpl::Purr(){
printf("purrrrrr");
}
I think most people refer to this as the Handle Body idiom. See James Coplien's book Advanced C++ Programming Styles and Idioms. It's also known as the Cheshire Cat because of Lewis Caroll's character that fades away until only the grin remains.
The example code should be distributed across two sets of source files. Then only Cat.h is the file that is shipped with the product.
CatImpl.h is included by Cat.cpp and CatImpl.cpp contains the implementation for CatImpl::Purr(). This won't be visible to the public using your product.
Basically the idea is to hide as much as possible of the implementation from prying eyes.
This is most useful where you have a commercial product that is shipped as a series of libraries that are accessed via an API that the customer's code is compiled against and linked to.
We did this with the rewrite of IONA's Orbix 3.3 product in 2000.
As mentioned by others, using his technique completely decouples the implementation from the interface of the object. Then you won't have to recompile everything that uses Cat if you just want to change the implementation of Purr().
This technique is used in a methodology called design by contract.
Because you want Purr() to be able to use private members of CatImpl. Cat::Purr() would not be allowed such an access without a friend declaration.
Because you then don't mix responsibilities: one class implements, one class forwards.
For what is worth, it separates the implementation from the interface. This is usually not very important in small size projects. But, in large projects and libraries, it can be used to reduce the build times significantly.
Consider that the implementation of Cat may include many headers, may involve template meta-programming which takes time to compile on its own. Why should a user, who just wants to use the Cat have to include all that? Hence, all the necessary files are hidden using the pimpl idiom (hence the forward declaration of CatImpl), and using the interface does not force the user to include them.
I'm developing a library for nonlinear optimization (read "lots of nasty math"), which is implemented in templates, so most of the code is in headers. It takes about five minutes to compile (on a decent multi-core CPU), and just parsing the headers in an otherwise empty .cpp takes about a minute. So anyone using the library has to wait a couple of minutes every time they compile their code, which makes the development quite tedious. However, by hiding the implementation and the headers, one just includes a simple interface file, which compiles instantly.
It does not necessarily have anything to do with protecting the implementation from being copied by other companies - which wouldn't probably happen anyway, unless the inner workings of your algorithm can be guessed from the definitions of the member variables (if so, it is probably not very complicated and not worth protecting in the first place).
If your class uses the PIMPL idiom, you can avoid changing the header file on the public class.
This allows you to add/remove methods to the PIMPL class, without modifying the external class's header file. You can also add/remove #includes to the PIMPL too.
When you change the external class's header file, you have to recompile everything that #includes it (and if any of those are header files, you have to recompile everything that #includes them, and so on).
Typically, the only reference to a PIMPL class in the header for the owner class (Cat in this case) would be a forward declaration, as you have done here, because that can greatly reduce the dependencies.
For example, if your PIMPL class has ComplicatedClass as a member (and not just a pointer or reference to it) then you would need to have ComplicatedClass fully defined before its use. In practice, this means including file "ComplicatedClass.h" (which will also indirectly include anything ComplicatedClass depends on). This can lead to a single header fill pulling in lots and lots of stuff, which is bad for managing your dependencies (and your compile times).
When you use the PIMPL idiom, you only need to #include the stuff used in the public interface of your owner type (which would be Cat here). Which makes things better for people using your library, and means you don't need to worry about people depending on some internal part of your library - either by mistake, or because they want to do something you don't allow, so they #define private public before including your files.
If it's a simple class, there's usually isn't any reason to use a PIMPL, but for times when the types are quite big, it can be a big help (especially in avoiding long build times).
Well, I wouldn't use it. I have a better alternative:
File foo.h
class Foo {
public:
virtual ~Foo() { }
virtual void someMethod() = 0;
// This "replaces" the constructor
static Foo *create();
}
File foo.cpp
namespace {
class FooImpl: virtual public Foo {
public:
void someMethod() {
//....
}
};
}
Foo *Foo::create() {
return new FooImpl;
}
Does this pattern have a name?
As someone who is also a Python and Java programmer, I like this a lot more than the PIMPL idiom.
Placing the call to the impl->Purr inside the .cpp file means that in the future you could do something completely different without having to change the header file.
Maybe next year they discover a helper method they could have called instead and so they can change the code to call that directly and not use impl->Purr at all. (Yes, they could achieve the same thing by updating the actual impl::Purr method as well, but in that case you are stuck with an extra function call that achieves nothing but calling the next function in turn.)
It also means the header only has definitions and does not have any implementation which makes for a cleaner separation, which is the whole point of the idiom.
We use the PIMPL idiom in order to emulate aspect-oriented programming where pre, post and error aspects are called before and after the execution of a member function.
struct Omg{
void purr(){ cout<< "purr\n"; }
};
struct Lol{
Omg* omg;
/*...*/
void purr(){ try{ pre(); omg-> purr(); post(); }catch(...){ error(); } }
};
We also use a pointer-to-base class to share different aspects between many classes.
The drawback of this approach is that the library user has to take into account all the aspects that are going to be executed, but only sees his/her class. It requires browsing the documentation for any side effects.
I just implemented my first PIMPL class over the last couple of days. I used it to eliminate problems I was having, including file *winsock2.*h in Borland Builder. It seemed to be screwing up struct alignment and since I had socket things in the class private data, those problems were spreading to any .cpp file that included the header.
By using PIMPL, winsock2.h was included in only one .cpp file where I could put a lid on the problem and not worry that it would come back to bite me.
To answer the original question, the advantage I found in forwarding the calls to the PIMPL class was that the PIMPL class is the same as what your original class would have been before you pimpl'd it, plus your implementations aren't spread over two classes in some weird fashion. It's much clearer to implement the public members to simply forward to the PIMPL class.
Like Mr Nodet said, one class, one responsibility.
I don't know if this is a difference worth mentioning but...
Would it be possible to have the implementation in its own namespace and have a public wrapper / library namespace for the code the user sees:
catlib::Cat::Purr(){ cat_->Purr(); }
cat::Cat::Purr(){
printf("purrrrrr");
}
This way all library code can make use of the cat namespace and as the need to expose a class to the user arises a wrapper could be created in the catlib namespace.
I find it telling that, in spite of how well-known the PIMPL idiom is, I don't see it crop up very often in real life (e.g., in open source projects).
I often wonder if the "benefits" are overblown; yes, you can make some of your implementation details even more hidden, and yes, you can change your implementation without changing the header, but it's not obvious that these are big advantages in reality.
That is to say, it's not clear that there's any need for your implementation to be that well hidden, and perhaps it's quite rare that people really do change only the implementation; as soon as you need to add new methods, say, you need to change the header anyway.

Which design is better: provide direct access to an owned object or give owning object forwarding methods to the owned object?

Which is better:
class Owner
{
public:
void SomeMethodA()
{
_ownee.SomeMethodA();
}
int SomeMethodB()
{
return _ownee.SomeMethodB();
}
private:
Ownee _ownee;
};
or this:
class Ownee
{
public:
void SomeMethodA();
int SomeMethodB();
};
class Owner
{
public:
Ownee& GetOwnee() const
{
return _ownee;
}
private:
Ownee _ownee;
};
I seem to recall reading long ago that the first option is better than the second option, but I can't remember why. I want to say because there is less coupling between users of Owner and Ownee. Clients would only need to know about Owner's interface and not Ownee's whereas with the second option clients would need to be aware of both Owner's and Ownee's interfaces.
One's not superior in every regard, in every case. However, wrapping the interfaces and encapsulating the members (the first one) is generally preferable.
A class and its members have special relationships. A class often uses its interface to restrict functionality to operate within the domain it is intended, and it may be used to for additional internal state validation and to improve program correctness.
When well encapsulated, the Owner has far more freedom to change its implementation or members as needed.
Exposing members can often lead to higher coupling, and ultimately push a lot of long term maintenance onto the client (resulting in more bugs, and redundant implementations for the client). A rather obvious example of this: assume the Owner has two members, and thread safety must be guaranteed -- it makes little sense to push that responsibility onto the clients, and to expect the clients to implement and maintain thread safety over several changes over several years. However, the Owner can abstract all that, and alter its implementation appropriately when its implementation changes, or prevent changes to members (Ownee) from affecting clients in this regard.
Changes to the classes (either Owner or Ownee) will generally affect the client far less when its members are not exposed, and the class (Owner) provides a strict, simple interface to its functionalities.
'Performance' is often regarded as a reason to favor the second ("Just provide clients accessors"). I find that an unfounded over-simplification. Performance may be better or it may worse! It depends on many, many things in C++ when developing nontrivial programs. Again, using the locking example: a bad interface of the first and/or favoring public accessors can require far more locking. As well, the optimizer has locality of the information and its members. There may be a good amount of internal implementation and methods provided by Owner -- if that's largely private, and uses static dispatch, it can result in a very small set of exported (or inline, if you favor) methods. An accessor in itself may not be so bad, but operations and dependencies on the accessed may push a lot of instructions and dependencies out to your clients -- when your internal implementation of Owner may represent all that in a single, compact, optimized form. In C++, abstraction layers can be very cheap (often nothing if done well) when optimized. Performance swings both ways here in the real world, and depends on many variables.
Most often, I use the first form. When I use the second form, it's often with:
Private/Inner classes.
or as components of a larger system (e.g. meta-programming).
Reads:
http://en.wikipedia.org/wiki/Law_Of_Demeter
http://en.wikipedia.org/wiki/Cohesion_(computer_science)
http://en.wikipedia.org/wiki/Coupling_(computer_science)
http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
http://en.wikipedia.org/wiki/Information_hiding
You are thinking of the Pimpl (pointer to implementation) idiom.
One nice way to do this is to declare the implementation class in the header file and define it in the .c file; this ensures that no one can see the details via .h inclusion.
.h file
#ifndef object_INCLUDED
#define object_INCLUDED
#include <boost/scoped_ptr.hpp>
class Object
{
public:
//...
private:
class ObjectImpl;
boost::scoped_ptr<ObjectImpl> impl_;
}
#endif
.c file
#include "object.h"
//==================================================
// Implementation of ObjectImpl
//==================================================
class Object::ObjectImpl
{
public:
ObjectImpl(int);
int value() const;
private:
int val_;
};
Object::ObjectImpl::ObjectImpl(int val)
: val_(val)
{}
int
Object::ObjectImpl::value() const
{
return val_;
}
//==================================================
// Implementation of Object
//==================================================
Object::Object(int val)
: impl_(new ObjectImpl(val))
{
}

Static members class vs. normal c-like interface

Hey there.
After reading here about the Service Locator pattern, it got me thinking wether a class with only static members really is the way to go, or if a normal c-like interace wouldn't be more appropriate. I see people throwing around the class keyword all the time when they don't even need it.
Example with static members class taken from the linked page:
class Locator
{
public:
static IAudio* GetAudio() { return service_; }
static void Register(IAudio* service)
{
service_ = service;
}
private:
static IAudio* service_;
};
Here's a way one could do it too:
// in .h
namespace Locator{
IAudio* GetAudio();
void Register(IAudio* service);
}
// in .cpp
namespace Locator{
namespace {
IAudio* service_;
}
IAudio* GetAudio() {
return service_;
}
void Register(IAudio* service) {
service_ = service;
}
}
Both examples can be called exactly the same way with Locator::GetAudio() and Locator::Register(...).
Is one of the above superior to the other? Are they the same? Are there maybe better ways to accomplish this? Or is it just about personal preferences? Thanks for any help. :)
Your proposal with namespaces has a slight weakness in maintainability - if you need to change the interface for some reason, you have to remember to change both the interface (.h) and implementation (.cpp), or a mismatch may not be detected until link time. If you use a class, then the compiler can detect an error such as a number of parameters mismatch.
On the other hand, since the implementation (service_) in your case only appears in the .cpp file, you may be able to change the private implementation of the locator without forcing a recompile of code that depends on the locator. (Common class-based patterns can provide this same encapsulation.)
These are fairly minor differences. A public namespace containing functions is almost exactly the same as a class with only static member functions.
one good reason for using class interfaces is consistency.
often, there will be supporting implementation or subclass use of the shared data in the Locator class. therefore, it is preferable (to many people) to use one approach across their codebase, rather than combining namespaces and classes for their static data (since some implementations may extend or specialize the service).
many people don't like dealing with static data. some issues from the above examples are: thread safety, ownership, and the lifetime of the data. the data and the implementations can be easier to maintain if these are restricted to a class scope (rather than a file scope). these issues grow as the program's complexity grows -- the example you have posted is very simple.
namespace labels/aliases are more difficult to pass around (compared to types/typedefs/template parameters). this is useful if your interfaces are similar and you are using a good amount of generic programming, or if you simply want to implement tests.

Hide class type in header

I'm not sure if this is even possible, but here goes:
I have a library whose interface is, at best, complex. Unfortunately, not only is it a 3rd-party library (and far too big to rewrite), I'm using a few other libraries that are dependent on it. So that interface has to stay how it is.
To solve that, I'm trying to essentially wrap the interface and bundle all the dependencies' interfaces into fewer, more logical classes. That part is going fine and works great. Most of the wrapper classes hold a pointer to an object of one of the original classes. Like so:
class Node
{
public:
String GetName()
{
return this->llNode->getNodeName();
}
private:
OverlyComplicatedNodeClass * llNode; // low-level node
};
My only problem is the secondary point of this. Beside simplifying the interface, I'd like to remove the requirement for linking against the original headers/libraries.
That's the first difficulty. How can I wrap the classes in such a way that there's no need to include the original headers? The wrapper will be built as a shared-library (dll/so), if that makes it simpler.
The original classes are pointers and not used in any exported functions (although they are used in a few constructors).
I've toyed with a few ideas, including preprocessor stuff like:
#ifdef ACCESSLOWLEVEL
# define LLPtr(n) n *
#else
# define LLPtr(n) void *
#endif
Which is ugly, at best. It does what I need basically, but I'd rather a real solution that that kind of mess.
Some kind of pointer-type magic works, until I ran into a few functions that use shared pointers (some kind of custom SharedPtr<> class providing reference count) and worse yet, a few class-specific shared pointers derived from the basic SharedPtr class (NodePtr, for example).
Is it at all possible to wrap the original library in such a way as to require only my headers to be included in order to link to my dynamic library? No need to link to the original library or call functions from it, just mine. Only problem I'm running into are the types/classes that are used.
The question might not be terribly clear. I can try to clean it up and add more code samples if it helps. I'm not really worried about any performance overhead or anything of this method, just trying to make it work first (premature optimization and all that).
Use the Pimpl (pointer to implementation) idiom. As described, OverlyComplicatedNodeClass is an implementation detail as far as the users of your library are concerned. They should not have to know the structure of this class, or even it's name.
When you use the Pimpl idiom, you replace the OverlyComplicatedNodeClass pointer in your class with a pointer to void. Only you the library writer needs to know that the void* is actually a OverlyComplicatedNodeClass*. So your class declaration becomes:
class Node
{
public:
String GetName();
private:
void * impl;
};
In your library's implementation, initialize impl with a pointer to the class that does the real work:
my_lib.cpp
Node::Node()
: impl(new OverlyComplicatedNodeClass)
{
// ...
};
...and users of your library need never know that OverlyComplicatedNodeClass exists.
There's one potential drawback to this approach. All the code which uses the impl class must be implemented in your library. None if it can be inline. Whether this is a drawback depends very much on your application, so judge for yourself.
In the case of your class, you did have GetName()'s implementation in the header. That must be moved to the library, as with all other code that uses the impl pointer.
Essentially, you need a separate set of headers for each use. One that you use to build your DLL and one with only the exported interfaces, and no mention at all of the encapsulated objects. Your example would look like:
class Node
{
public:
String GetName();
};
You can use preprocessor statements to get both versions in the same physical file if you don't mind the mess.

Why should the "PIMPL" idiom be used? [duplicate]

This question already has answers here:
Is the PIMPL idiom really used in practice?
(12 answers)
Closed 8 years ago.
Backgrounder:
The PIMPL Idiom (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.
This hides internal implementation details and data from the user of the library.
When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?
To illustrate, this code puts the Purr() implementation on the impl class and wraps it as well.
Why not implement Purr directly on the public class?
// header file:
class Cat {
private:
class CatImpl; // Not defined here
CatImpl *cat_; // Handle
public:
Cat(); // Constructor
~Cat(); // Destructor
// Other operations...
Purr();
};
// CPP file:
#include "cat.h"
class Cat::CatImpl {
Purr();
... // The actual implementation can be anything
};
Cat::Cat() {
cat_ = new CatImpl;
}
Cat::~Cat() {
delete cat_;
}
Cat::Purr(){ cat_->Purr(); }
CatImpl::Purr(){
printf("purrrrrr");
}
I think most people refer to this as the Handle Body idiom. See James Coplien's book Advanced C++ Programming Styles and Idioms. It's also known as the Cheshire Cat because of Lewis Caroll's character that fades away until only the grin remains.
The example code should be distributed across two sets of source files. Then only Cat.h is the file that is shipped with the product.
CatImpl.h is included by Cat.cpp and CatImpl.cpp contains the implementation for CatImpl::Purr(). This won't be visible to the public using your product.
Basically the idea is to hide as much as possible of the implementation from prying eyes.
This is most useful where you have a commercial product that is shipped as a series of libraries that are accessed via an API that the customer's code is compiled against and linked to.
We did this with the rewrite of IONA's Orbix 3.3 product in 2000.
As mentioned by others, using his technique completely decouples the implementation from the interface of the object. Then you won't have to recompile everything that uses Cat if you just want to change the implementation of Purr().
This technique is used in a methodology called design by contract.
Because you want Purr() to be able to use private members of CatImpl. Cat::Purr() would not be allowed such an access without a friend declaration.
Because you then don't mix responsibilities: one class implements, one class forwards.
For what is worth, it separates the implementation from the interface. This is usually not very important in small size projects. But, in large projects and libraries, it can be used to reduce the build times significantly.
Consider that the implementation of Cat may include many headers, may involve template meta-programming which takes time to compile on its own. Why should a user, who just wants to use the Cat have to include all that? Hence, all the necessary files are hidden using the pimpl idiom (hence the forward declaration of CatImpl), and using the interface does not force the user to include them.
I'm developing a library for nonlinear optimization (read "lots of nasty math"), which is implemented in templates, so most of the code is in headers. It takes about five minutes to compile (on a decent multi-core CPU), and just parsing the headers in an otherwise empty .cpp takes about a minute. So anyone using the library has to wait a couple of minutes every time they compile their code, which makes the development quite tedious. However, by hiding the implementation and the headers, one just includes a simple interface file, which compiles instantly.
It does not necessarily have anything to do with protecting the implementation from being copied by other companies - which wouldn't probably happen anyway, unless the inner workings of your algorithm can be guessed from the definitions of the member variables (if so, it is probably not very complicated and not worth protecting in the first place).
If your class uses the PIMPL idiom, you can avoid changing the header file on the public class.
This allows you to add/remove methods to the PIMPL class, without modifying the external class's header file. You can also add/remove #includes to the PIMPL too.
When you change the external class's header file, you have to recompile everything that #includes it (and if any of those are header files, you have to recompile everything that #includes them, and so on).
Typically, the only reference to a PIMPL class in the header for the owner class (Cat in this case) would be a forward declaration, as you have done here, because that can greatly reduce the dependencies.
For example, if your PIMPL class has ComplicatedClass as a member (and not just a pointer or reference to it) then you would need to have ComplicatedClass fully defined before its use. In practice, this means including file "ComplicatedClass.h" (which will also indirectly include anything ComplicatedClass depends on). This can lead to a single header fill pulling in lots and lots of stuff, which is bad for managing your dependencies (and your compile times).
When you use the PIMPL idiom, you only need to #include the stuff used in the public interface of your owner type (which would be Cat here). Which makes things better for people using your library, and means you don't need to worry about people depending on some internal part of your library - either by mistake, or because they want to do something you don't allow, so they #define private public before including your files.
If it's a simple class, there's usually isn't any reason to use a PIMPL, but for times when the types are quite big, it can be a big help (especially in avoiding long build times).
Well, I wouldn't use it. I have a better alternative:
File foo.h
class Foo {
public:
virtual ~Foo() { }
virtual void someMethod() = 0;
// This "replaces" the constructor
static Foo *create();
}
File foo.cpp
namespace {
class FooImpl: virtual public Foo {
public:
void someMethod() {
//....
}
};
}
Foo *Foo::create() {
return new FooImpl;
}
Does this pattern have a name?
As someone who is also a Python and Java programmer, I like this a lot more than the PIMPL idiom.
Placing the call to the impl->Purr inside the .cpp file means that in the future you could do something completely different without having to change the header file.
Maybe next year they discover a helper method they could have called instead and so they can change the code to call that directly and not use impl->Purr at all. (Yes, they could achieve the same thing by updating the actual impl::Purr method as well, but in that case you are stuck with an extra function call that achieves nothing but calling the next function in turn.)
It also means the header only has definitions and does not have any implementation which makes for a cleaner separation, which is the whole point of the idiom.
We use the PIMPL idiom in order to emulate aspect-oriented programming where pre, post and error aspects are called before and after the execution of a member function.
struct Omg{
void purr(){ cout<< "purr\n"; }
};
struct Lol{
Omg* omg;
/*...*/
void purr(){ try{ pre(); omg-> purr(); post(); }catch(...){ error(); } }
};
We also use a pointer-to-base class to share different aspects between many classes.
The drawback of this approach is that the library user has to take into account all the aspects that are going to be executed, but only sees his/her class. It requires browsing the documentation for any side effects.
I just implemented my first PIMPL class over the last couple of days. I used it to eliminate problems I was having, including file *winsock2.*h in Borland Builder. It seemed to be screwing up struct alignment and since I had socket things in the class private data, those problems were spreading to any .cpp file that included the header.
By using PIMPL, winsock2.h was included in only one .cpp file where I could put a lid on the problem and not worry that it would come back to bite me.
To answer the original question, the advantage I found in forwarding the calls to the PIMPL class was that the PIMPL class is the same as what your original class would have been before you pimpl'd it, plus your implementations aren't spread over two classes in some weird fashion. It's much clearer to implement the public members to simply forward to the PIMPL class.
Like Mr Nodet said, one class, one responsibility.
I don't know if this is a difference worth mentioning but...
Would it be possible to have the implementation in its own namespace and have a public wrapper / library namespace for the code the user sees:
catlib::Cat::Purr(){ cat_->Purr(); }
cat::Cat::Purr(){
printf("purrrrrr");
}
This way all library code can make use of the cat namespace and as the need to expose a class to the user arises a wrapper could be created in the catlib namespace.
I find it telling that, in spite of how well-known the PIMPL idiom is, I don't see it crop up very often in real life (e.g., in open source projects).
I often wonder if the "benefits" are overblown; yes, you can make some of your implementation details even more hidden, and yes, you can change your implementation without changing the header, but it's not obvious that these are big advantages in reality.
That is to say, it's not clear that there's any need for your implementation to be that well hidden, and perhaps it's quite rare that people really do change only the implementation; as soon as you need to add new methods, say, you need to change the header anyway.