Friend function

From Wikipedia, the free encyclopedia

A friend function is used in object-oriented programming to allow access to private or protected data 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.

Contents

[edit] 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.

#include <iostream>
using namespace std;
 
class B;
class 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 <<"\n"<<"B::b=" <<y.b<<endl;
}
int main()
{
   A a;
   B b;
   show(a,b);
}

[edit] See also

[edit] References

  • An Introduction to Object-Oriented Programming in C++ by Graham M. Seed

[edit] External links