Masking implementations can be done by PIMPL idiom or using simple polymorphism, which is a Factory method pattern. Basically, you create an interface class, say IA
like so:
/* File: A.h */
#include <memory> /* For std::shared_ptr */
class IA;
/* Change the line below to boost::shared_ptr<> or
* another implementation of a shared-pointer.
* Read more:
* http://en.wikipedia.org/wiki/Smart_pointer#shared_ptr_and_weak_ptr
*/
typedef std::shared_ptr<IA> APtr;
class IA {
public:
static APtr Create(const int foo);
IA(){}
virtual ~IA(){}
virtual void somePublicMethod() = 0;
};
In your A.cpp you'll have it's implementation:
/* File: A.cpp */
#include "A.h"
class A : public IA
{
public:
A(const int foo):foo_(foo){}
void somePublicMethod(){/* Your awesome implementation goes here */}
};
APtr IA::Create(const int foo)
{
return APtr(new A(foo));
}
This way, you pass around only the interface and expose only the public methods to outside world, which the internals are in your CPP files.
Advantages:
- Hide implementation completely from users
Disadvantages:
- You'll need to create an interface for every class you intend to hide
- Your users will have to call the factory method to create an instance. For e.g.
Create()
in the above example.
- You will always have your class instances to be in heap memory than in stack, i.e., your implementation instances will always have to be a pointer. (Read More: Heap vs. Stack Memory)