shap@polya.Stanford.EDU (Jonathan S. Shapiro) (10/14/88)
I mentioned in this group a way to hide the private part, and a couple
of people have inquired for more info by mail. Since it seems to be of
general interest, I will post it.
Consider a class:
class Contrived {
int i;
float f;
public:
Contrived();
~Contrived();
short fred;
long wilma;
} ;
The idea is to separate the private part by rendering it a structure:
class Contrived2 {
struct Contrived_Private {
int i;
float f;
} p;
public:
Contrived()
: p(args);
~Contrived();
short fred;
long wilma;
} ;
Note that where you previously refered to Object.i from within a
member function, you now need to refer to Object.p.i, which is
inconvenient, but perhaps acceptable.
The final step is then to remove the structure definition, changing
the class to:
class Contrived3 {
union {
struct Contrived_Private& p;
struct Contrived_Private *pptr;
} /* ANONYMOUS */;
public:
Contrived();
~Contrived();
short fred;
long wilma;
} ;
Note that because Contrived_Private is a *reference*, it is not
necessary to have the structure defined, and the Constructor is now
free to contain code like:
Old Form New Form
Contrived() Contrived()
: p(pargs); {
{ ... } pptr = new Contrived_Private(pargs);
/* references through p now work */
... }
A cleaner answer that might or might not work would be just to drop
the pptr and the anonymous union leaving Contrived_Private& p, and
try:
Contrived()
: p(*(new Contrived_Private(pargs)))
{...}
Of course, the destructor then has to do so tricky casts to delete it
correctly.
Does that help?
Jon