Content deleted Content added
No edit summary |
m →Use cases: consistently "method" (already three times in the intro and also category) |
||
(28 intermediate revisions by 20 users not shown) | |||
Line 1:
In [[object-oriented programming]], a '''friend function''', that is a "friend" of a given [[class (computer science)|class]], is a function that is given the same access as methods to private and protected [[data]].<ref>{{cite book|last=Holzner|first=Steven|title=C++ : Black Book|year=2001|publisher=Coriolis Group|___location=Scottsdale, Ariz.|isbn=1-57610-777-9|page=397|quote=When you declare a function a friend of a class, that function has access to the internal data members of that object (that is, its protected, and private data members.)}}
</ref>
A friend function is declared by the class that is granting access, so friend functions are part of the class interface, like methods. Friend functions allow alternative syntax to use objects, for instance <code>f(x)</code> instead of <code>x.f()</code>, or <code>g(x,y)</code> instead of <code>x.g(y)</code>. Friend functions have the same implications on [[separation of concerns|encapsulation]] as methods.
A similar concept is that of [[friend class]].
==Use cases==
This approach may be used in friendly function when a function needs to access private data in objects from two different classes.
This may be accomplished in two similar ways:
*
*
<
// C++ implementation of friend functions.
#include <iostream>
using namespace std;
class Foo; // Forward declaration of class Foo in order for example to compile.
class Bar {
private:
int a = 0;
public:
void show(Bar& x, Foo& y);
friend void show(Bar& x, Foo& y); // declaration of global function as friend
};
class Foo {
private:
int b = 6;
public:
friend void
friend void Bar::show(Bar& x, Foo& y); // declaration of
▲ friend void Bar::show(Bar& x, Foo& y); // declaration of friend from other class
};
// Definition of a
void Bar::show(Bar& x, Foo& y) {
cout << "Show via function member of Bar" << endl;
Line 56 ⟶ 55:
a.show(a,b);
}
</syntaxhighlight>
==References==
{{reflist}}
* [[The C++ Programming Language]] by [[Bjarne Stroustrup]]
Line 64 ⟶ 63:
==External links==
*[http://www.codersource.net/c/ctutorials/ctutorialfriend.aspx C++ friend function tutorial] at CoderSource.net
[[Category:Method (computer programming)]]
[[Category:Articles with example C++ code]]
|