Friend function

Under a friend function or Friend method is understood in object-oriented programming, a method, function or procedure that one allowed on private ( private ) or protected (protected) access data of another class, to which she would not have access otherwise.

Such access is contrary to the paradigm of data encapsulation, but can still be useful in certain circumstances. Then the accessing method with the keyword friend as a "friend" that declares it 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 caution, as this data encapsulation is weakened. Friend Methods are a concept of the programming language C . However, there are similar opportunities in other object-oriented programming languages ​​(for example, internal in C #).

Examples

This C example, the main () method is a friend of class A. You can therefore access to the protected attribute value in its class. Had it not been declared as a friend, would be an access is not possible and the program could not be translated.

# include   class A { protected:     int value;   public:     A (): value (42 ) {}     friend int main (); };   int main () {     A a;       std :: cout << " A :: value =" << std :: endl << a.wert; } Friend class

Instead of a method may involve a whole class can be defined as a friend of another class. Then each method of this class can access all the 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);      a.show (); / / Returns "a = 100 " from      b.show (); / / Returns "b = 200 " from      b.changeA (a);      a.show (); / / Returns "a = 200 " from      b.show (); / / Returns "b = 200 " from } literature

  • Bjarne Stroustrup: The C Programming Language. ISBN 978-0-201-88954-3.
  • Graham M. Seed: An Introduction to Object-Oriented Programming in C . ISBN 978-1-85233-450-5.

Pictures of Friend function

111975
de