- Friend function
A friend function is used in
object-oriented programming to allow access to private or protecteddata in a class from outside the class. Normally a function which is not a member of a class cannot access such information; neither can an external class. Occasionally such access will be advantageous for the programmer; under these circumstances, the function or external class can be declared as a friend of the class using the keyword "friend." The function or external class will then have access to all information – public, private or protected – within the class.This procedure should be used with caution. If too many functions or external classes are declared as friends of a class with protected or private data, necessary
data security may be compromised, as well as the encapsulation of separate classes in object-oriented programming.Example
The following is an example of friend function's usage. The function show() is a friend of classes A and B which is used to display the private members of A and B. Instead of writing a separate function in each of the classes only one friend function can be used to display the data items of both the classes.
#includeusing namespace std; class B; // Forward declaration of class B in order for example to compileclass A{private: int a;public: void A() { a=0; } friend void show(A& x, B& y);};
class B{private: int b;public: void B() { b=0; } friend void show(A& x, B& y);};
void show(A& x, B& y){ cout << "A::a=" << x.a << endl; cout << "B::b=" << y.b << endl;}
int main(){ A a; B b; show(a,b);}
ee also
*
friend class References
*An Introduction to Object-Oriented Programming in C++ by Graham M. Seed
External links
* [http://www.codersource.net/cpp_tutorial_friend.html C++ friend function tutorial] at CoderSource.net
* [http://www.cplusplus.com/doc/tutorial/inheritance.html C++ friendship and inheritance tutorial] at cplusplus.com
Wikimedia Foundation. 2010.