On Thu, Mar 13, 2003 at 01:02:35AM +0200, Tuomo Valkonen wrote:
> As I mentioned, my C++ is very rusty, so here's another question:
> Is it somehow possible, without doing it individually for all those
> functions, to define non-class functions in a file "friends" for a
> class so that protections don't apply? I'd hate to have to introduce
> every minor helper function in the class body. If it is not possible,
> then I'd have to use no protections at all if I ever decide to use
> c++ classes.
Firstly, how to do it then why you shouldn't.
How to do it:
Put all the functions in a separate class that's a friend of the main class.
class MyPublicClass {
public:
void public_function();
private:
int private_var;
friend class MyLittleHelper;
};
class MyLittleHelper {
public:
static void sneaky(MyPublicClass &);
};
void MyLittleHelper::sneaky(MyPublicClass &o) {
o.private_var++;
}
void main() {
MyPublicClass o();
o.public_function();
MyLittleHelper::sneaky(o);
}
You can make class MyLittleHelper a friend of as many classes as you like so
you can give it unrestricted access to all your internals.
Why you shouldn't do it:
If you have to do it then your design is all messed up!
private/protected/public are there to support data hiding. If you need to
work around them then why bother using them at all?
What you should do:
Either:
1) Declare everything public, and comments to the class declaration saying
"don't call this function" or "for internal use only" or words to that
effect. Data hiding isn't needed when you trust the people using your code
:-)
2) Declare all helper functions to be private or protected as appropriate.
If you find you need to access private member variabless of more than one class
then add a public accessor (or make the variable public). If you need to
fiddle with the privates of two classes at the same time then your design
is messed up.
I recommend option 1. As Ion is currently being developed just make
everything public and worry about private/protected when things have
stabilised.
Regards,
Tom