Opaque Pointer Pattern in C++ -- Daniel Sieger
After reading this article, you should understand the basics of the opaque pointer pattern and how you can implement it using std::unique_ptr
. I also gave some hints on when it is appropriate to use it and when maybe not.
Opaque Pointer Pattern in C++
by Daniel Sieger
From the article:
The basic problem is that C++ class declarations expose private details of the class. Private member functions and data members need to be declared in the header. Here’s an example for illustration:
// Point.h
class Point
{
public:
Point(float x, float y);
float x();
float y();
private:
float x_;
float y_;
};
While users of this class don’t have direct access to the private data members x_ and y_, there is still a dependency: If you change the private implementation details of Point, all other compilation units that include Point.h know about the change and need to be re-compiled.
This only gets worse for more complex dependency chains, e.g., when there are dependencies to other classes internal to the module that need to be included. To a certain degree, this can be dealt with by using forward declarations. However, at the end of the day there is an information leak: Private implementation details are leaking to clients. This goes directly against the idea of information hiding.
The opaque pointer pattern helps to deal with this problem.