Friend function

from Wikipedia, the free encyclopedia

Under a friend function or Friend method refers to the object-oriented programming a method , function or procedure that is allowed (to private individual ) or protected ( protected ) data of another class access to which they would not have access otherwise.

Such access contradicts the paradigm of data encapsulation , but can still be useful under certain circumstances. Then the accessing method is declared with the keyword friend as a "friend" of the accessed class. She then not only to public ( public ), but also to protected ( protected ) or private ( private ) information in this class access.

This possibility of friendship should be used with care, as it weakens the data encapsulation. Friend methods are a concept of the C ++ programming language . However, there are similar possibilities in other object-oriented programming languages ​​(for example internal in C # ).


example 1

In this C ++ example, the function is main()a friend of the class A. It can therefore access the privateprotected attribute of wertthis class. If it were main()not declared as a friend, access to the private attribute would not be possible and the program could not be translated either.

A preferred solution in practice would be an access function in this example .

#include <iostream>

class A {
   int wert;
   A() : wert(42) {}
   friend int main();

int main() {
   A a;

   std::cout << "A::wert = " << a.wert << std::endl;

Example 2

Operators can be overloaded in C ++. So z. B. also with the output operator <<(originally logical shift ). If you implement your own data types, you can control the output by overloading this operator. This often requires access to private members that are normally <<not accessible to the operator .

However, by friendmarking the globally overloaded operator with , private attributes can also be output:

#include <iostream>
using namespace std;

class Zahl {
    int m_zahl{20};
    Zahl(int zahl) : m_zahl(zahl){}

    friend ostream& operator<<(ostream &out, const Zahl &zahlObj){
        out << "Zahl: " << zahlObj.m_zahl;
        return out;

int main(){
    Zahl zahl{5}
    cout << zahl << endl; //Ausgabe: Zahl: 5

Note that although this operator Zahlis defined within the class , it is a free function; H. is not a member function of the class Zahl. If you omit the keyword friend, it becomes operator<<a member function, which, however, would not make sense for this example of standard output.

Friend class

A whole, instead of a method class as a friend of another class are defined. Then each method of this class can access all private information of the other class.

class A
    friend class B;

class B
    void changeA(A &a) { a.a = b; }

int main()
    A a(100);
    B b(200);; // Gibt "a = 100" aus; // Gibt "b = 200" aus
    b.changeA(a);; // Gibt "a = 200" aus; // Gibt "b = 200" aus


Web links