shapiro@inria.UUCP (Marc Shapiro) (03/10/87)
I would like to suggest an addition to the C++ information-hiding
mechanism. I feel there is a need for a scoping attribute, intermediate
between 'protected' and 'private'.
Here is the context: in my system all classes derive utlimately from a base
class sosObject. In this class I define all the operations which are common
to all types of objects, but which I consider internal to each instance.
For example, I have an operation "write_me_to_disk", the code for which is
generic (write from base-address to known size into known file), but it
should be applied only to self. In other words, this->write_me_to_disk() is
legal, but x->write_me_to_disk() is wrong, because I can't know if x is in a
consistent state.
The current protection scheme doesn't support this, which I feel is a common
need. 'Public' of course is ruled out; 'private' does not allow derived
classes to inherit write_me_to_disk. 'protected' doesn't do the trick
either, because ANY derived class has access to the protected methods:
class sosObject {
long size;
int fd;
protected:
write_me_to_disk () {return ::write(fd, (void*)this, size);}
}
class A: public sosObject {
...
}
class B: public sosObject {
foo (A *a) { a -> write_me_to_disk(); } // legal !
}
The above example shows that even though B is not derived from A, B has
access to A's 'protected' members.
Therefore I suggest adding a new protection keyword, e.g. "self" (or "this")
such that the operations protected by "self" may be applied only to "this".
class sosObject {
self:
write_me_to_disk () {...}
}
class A: public sosObject {
foo () {... ; write_me_to_disk() ; ...} // legal
}
class B: public sosObject {
bar (A *a) { a -> write_me_to_disk(); } // illegal
quux (A *a) { a -> foo () } // legal
}
In this example 'foo' first puts the object into a consistent state, then
calls write_me_to_disk. (No, it is not feasible to do it directly in
write_me_to_disk. This is just an ultra-simplified example.)
I'm sure this proposal has many more uses than the example suggested here.
How hard would it be to implement it?
*AAwickma