In object-oriented programming, a friend function, that is a "friend" of a given class, is a function that is given the same access as methods to private and protected data. [1]
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 f(x)
instead of x.f()
, or g(x, y)
instead of x.g(y)
. Friend functions have the same implications on encapsulation as methods.
A similar concept is that of friend class.
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.importstd;// Forward declaration of class Foo in order for example to compile.classFoo;classBar{private:inta=0;public:// Definition of a method of Bar; this is a friend of Foovoidshow(Bar&x,Foo&y){std::println("Show via function member of Bar");std::println("Bar::a = {}",x.a);std::println("Foo::b = {}",y.b);}friendvoidshow(Bar&x,Foo&y);// declaration of global function as friend};classFoo{private:intb=6;public:friendvoidshow(Bar&x,Foo&y);// declaration of global function as friendfriendvoidBar::show(Bar&x,Foo&y);// declaration of friend from other class};// Friend for Bar and Foo, definition of global functionvoidshow(Bar&x,Foo&y){std::println("Show via global function");std::println("Bar::a = {}",x.a);std::println("Foo::b = {}",y.b);}intmain(){Bara;Foob;show(a,b);a.show(a,b);}
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.)