Ask a Teacher
what is friend function and its use? |
In object-oriented programming, a friend function that is a "friend" of a given class is allowed access to private and protected data in that class that it would not normally be able to as if the data was public. Normally, a function that is defined outside of a class cannot access such information. Declaring a function a friend of a class allows this, in languages where the concept is supported. A friend function is declared by the class that is granting access, explicately stating what function from a class is allowed access. 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. Generallly though, friend functions are a good thing for encapsulation, as you can keep data of a class private from all except those who you explicately state need it, but this does mean your classes will become tightly coupled. |