What is Friend function,Friend Keyword

What is Friend function,Friend Keyword
A class can declare external functions or other classes as friends. Friendship grants full access to all of the grantor's members, even private and protected ones:
void encrypt (string & rep) {/*..*/} //global function
class spy {
public:
static void transmit(const string& rep) { /*..*/}
//...
};
class secret {
friend class spy;//spy can access all members of 'secret'
friend void encrypt(string & rep);//...and so can encrypt
private:
string report;
public:
void scramble() { ::encrypt(report); }
void transmit() const { spy::transmit(report); }
};
Notes about friendship:
A friend declaration exposes implementations details of its class, so it should be used wisely. However, friendship has the advantage of allowing code re-use in a simple manner; in fact, many of the standard functions and overloaded operators are used in standard containers (like string<>) by means of friendship.
Friendship is not inherited, so non-public members of any class derived from secret are not accessible to spy and encrypt.

No comments: