Wednesday, January 05, 2005

Friends are forever

The friend access for a function is a constant source of debate among C++ programmers. Inside a class declaration, we can specify an external function as friend and this function has access to all member variables of that class. Quite extra-ordinary decision in the language design, dont u think so ? One can say that this breaks the encapsulation, which is one of the primary goals for an object oriented language. Private members of a class are supposed to be accessed only by members of that class. Naturally. So the concept of friend is not at all advisable or so it seems. Atleast I thought so. But Bjarne Stroustrup could see that in a language with pointers, manipulating the private members is always possible. So the access control in C++ is designed to protect programmers from unintentional errors while coding (comiler can let them know when they access something they shouldnt) and not for protecting private members from programmers who intentionally want to access them. friend access to a function is explicitly granted by the class author. A function cannot declare itself as friend of a class and go ahead and access private members of any class it likes. Hence the class author is aware of another function which can access its private members and hence everything here is intentional. Suppose if there was no friend access, then the class author should either make the members public or provide methods for reading and writing to the private members. Actually this corrupts the public interface of the class. The author usually wouldnt want to do this just because another function needs access to its private members. If he does this, now the private members are read/write enabled from anywhere. Having friends are not that bad after all ;-)
I would say that friend access should be used with discretion, if ever. But in some cases you can have a better design by using friend functions instead of avoiding them because OO purists think that it will break encapsulation, but choose them with diligence..


Post a Comment

Subscribe to Post Comments [Atom]

<< Home