Re: Curious question about the STL ostream
On Sep 10, 8:38 am, "D. Susman" <derya.sus...@gmail.com> wrote:
The answer to why these methods have not been implemented as member
functions is because the more a class has member functions, the less
encapsulated it is (Scott Meyers has an article on this ). The public
interface of a class is determined as its member functions + non-
member functions operating on that class.
Yes and no. Part of the encapsulation of ostream is that <<
will work for any type which chooses to support it; i.e. the
class is intentionally open in this respect. In this case, the
choice of member or non member has been done very arbitrarily;
ideally, we'd like for all of the << operators to be members,
because this would result in the access rules we want. Ideally,
we don't want user defined operator << to be members, because
this would give them access to the internals of the class, but
in practice, given that it's an abstract base class, and that
all of the "documented" internals are available anyway, I don't
think that it's a real issue.
Of course, the standard could also have taken the point of view
that all of the << operators should be non-members. None of
them ever need access to the internals of the class. In this
sense, they really are an example of what Scott was talking
about. On the other hand, the conditions under which the
non-members can be called is less than ideal. (This would still
have been preferable to the current mix.)
One may not always have access to the source code of a big,
operational class. As requirements change and new functionalities
become necessary, one may code the new requirement as a non-member
function which is still a part of the interface of the class.
Declaring the functions as template members makes user defined
specializations possible.
Doing so extends the functionality of the class without
accessing the class file. You write a function whose first
parameter is that operational class and simply get along the
way.
This approach may sound freakish to the orthodox of Object
Oriented design, but it introduces a certain amount of
flexibility and class with designs fewer member functions.
It was, IMHO, a compromize based on many things, a lot of which
have since changed. The standard committee, by maintaining the
dicotomy, but changing the category of one of the types (char
const*), made a gratious change, for no good reason. Had they
made everything a member, using a template member function to
allow user defined specializations, or everything a non-member,
one could argue that the change at least improved coherence. As
it is, it was just an arbitrary means of breaking some existing
programs.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34