views:

499

answers:

3

One of classes in my program uses some third-party library. Library object is a private member of my class:

// My.h
    #include <3pheader.h>

    class My 
    {
    ...
    private:
       3pObject m_object;
    }

The problem with this - any other unit in my program that uses My class should be configured to include 3p headers. Moving to another kind of 3p will jeopardize the whole build... I see two ways to fix this - one is to is to make 3pObject extern and turn m_Object into a pointer, being initialized in constructor; second is to create an "interface" and "factory" classes and export them...

Could you suggest another ways to solve that ?

+12  A: 

The Private Implementation (PIMPL) pattern:

http://www.codeproject.com/KB/tips/PIMPL.aspx

Basically, you define that your class holds a pointer to a struct that you forward declare. Then you define the struct inside the cpp file and use the constructor and destructor in your class to create/delete the PIMPL.

:)

nlaq
+11  A: 

Use the "pimpl" idiom:

// header
class My
{
  class impl;
  std::auto_ptr<impl> _impl;
};

// cpp
#include <3pheader.h>
class My::impl
{
  3pObject _object;
};
1800 INFORMATION
Any reason not to use boost::scoped_ptr?
grigy
Nothing specific - I've been accustomed to using auto_ptr - it is probably more appropriate in this case to use scoped_ptr since there is no transfer of ownership
1800 INFORMATION
A: 

All of the internal structure of QT is done using private implementation classes.
You can look it up for a good reference on how it is done correctly.

shoosh