I know that friendship isn't inherited in C++, and have two questions.
(1) Why? Is it a technical problem, or just by design? If the latter,
isn't this a little prescriptive, and shouldn't there be a way of
explicitly inheriting friendship? (eg, class B : friendly public A)
(2) Is there a way I can simulate inheritance of friendship? I'm
working on an output library with a design based on that of iostreams:
there is a class called an OutputRegion which is fed strings through a
<< operator, processes them and displays them. I want the internal
workings of OutputRegion to be kept hidden directly from the library
user, but I do want them to be accessible by passing OutputModifiers to
<< (equivalent to iostream manipulators - eg, an OutputModifier called
NewLine which calls the OutputRegion's internal newLine function);
furthermore I want the user to be able to declare his own
OutputModifiers Here's a code snippet to illustrate what I mean:
////// begin code
class OutputModifier;
class OutputRegion
{
public:
OutputRegion& operator<< (string S)
{
/* do complicated things with S dependent on P */
return *this;
}
OutputRegion& operator<< (OutputModifier& O)
{ return O.Execute(*this); }
friend class OutputModifier;
private:
void newLine();
};
class OutputModifier
{
public:
friend class OutputRegion;
private:
virtual OutputRegion& Execute (OutputRegion& R)=0;
};
class NewLine : public OutputModifier
{
private:
OutputRegion& Execute (OutputRegion& R)
{
r.newLine(); // error here - newLine is private in this context
return R;
}
};
////// end code
(Apologies if this code doesn't compile right away - for reasons too
complicated to bother with here, my dev machine isn't connected to the
internet right now so I'm typing this from memory. I think it should be
ok barring, eg, missing semicolons).
Is there an easy way I can make this work? Or a way of simulating the
same effect, without exposing much more? Or is my design just all
wrong?
Thanks very much,
Tom