Friend function
|
|
Please expand this article. Some suggested sources are given hereafter. More information might be found in a section of the talk page. (October 2011) |
A friend function for a class is used in object-oriented programming to allow access to public, private, or protected data in the class from the outside. Normally, a function that 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 friend keyword.
A friend function is declared by the class that is granting access. Friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords.
A similar concept is that of friend class.
Friends should be used with caution. Too many functions or external classes declared as friends of a class with protected or private data may lessen the value of encapsulation of separate classes in object-oriented programming and may indicate a problem in the overall architecture design.
[edit] Use cases
This approach may be used when a function needs to access private data in objects from two different classes. This may be accomplished in two similar ways:
- a function of global or namespace scope may be declared as friend of both classes
- a member function of one class may be declared as friend of another one.
#include <iostream> using namespace std; class B; // Forward declaration of class B in order for example to compile class A { private: int a; public: A() { a = 0; } void show(A& x, B& y); friend void ::show(A& x, B& y); // declaration of global friend }; class B { private: int b; public: B() { b = 6; } friend void ::show(A& x, B& y); // declaration of global friend friend void A::show(A& x, B& y); // declaration of friend from other class }; // Definition of a member function of A; this member is a friend of B void A::show(A& x, B& y) { cout << "Show via function member of A" << endl; cout << "A::a = " << x.a << endl; cout << "B::b = " << y.b << endl; } // Friend for A and B, definition of global function void show(A& x, B& y) { cout << "Show via global function" << endl; cout << "A::a = " << x.a << endl; cout << "B::b = " << y.b << endl; } int main() { A a; B b; show(a,b); a.show(a,b); }
[edit] References
[edit] External links
- C++ friend function tutorial at CoderSource.net
- C++ friendship and inheritance tutorial at cplusplus.com