TITLE: separating interface and implementation using references

(Source: Patterns Digest V99 #19)

ANDREAS: Geisler Andreas <Andreas.Geisler@erls.siemens.de>

[snip]

In the context of separating interface and implementation
in C++, or to be precise, when I want to get rid of a class' state
in the header file, I usually employ the following:

--------------------------------------------------------------------
// file: X.hpp

class X
{
public:
  		X();
  virtual void	f();
  virtual		~X();
private:
  virtual void	someTemplateMethod();

protected:
  struct State;
  State& state;
};

---------------------------------------------------------------

// file: X.cpp

#include "X.hpp"
#include "Y.hpp"

struct X::State : public Y
{
  State() : x(0);
  int	x;
  // further non-virtual functions and members go here
};

X::X() : state(*new State())
{
}

X::~X()
{
  delete &state;
}

void X::f()
{
  state.x = 42;	// member access is through this->state. now, not this->
  state.methodOfY(); 
  someTemplateMethod();
}
---------------------------------------------------------------

This way, I can get rid of all non-virtual private
or protected members of an abstraction and
avoid including "Y.hpp" into "X.hpp".

I call this idiom "Hidden State".

Note that this pattern/idiom is only about separating
interface and state of a class, not interface and
the whole implementation like e.g. the Bridge Pattern.

[snip]
