this is a presentation on friend function, helpful especially to students studying in GTU, for subject of object oriented programming using C++ i.e. OOPC
2. FRIEND FUNCTION
While learning C++, we have emphasized on the fact that private members
cannot be accessed from outside the class i.e. A non member function cannot
have access to the private data of a class.
However, there could arise a situation where we would like 2 classes to share
a particular function.
In such situations, C++ allows a common function to be made friendly with
both the classes, allowing the function to have access to the private members
of these classes outside the class.
This can be seen as a real life analogy, where is a person would like to come
in your house, then you need to declare him as your friend so that I can access
your private resources.
3. Syntax of the friend function is given below
Function declared with the keyword friend is called friend
function.
4. Some special characteristics of friend function are as
follows:
It is not in the scope of the class to which it has been declared
as friend.
It can be invoked like a normal function without any object
needed.
Unlike Member function, it cannot access the member names
directly, and has to use object name and dot membership
operator with each member name.
It can be declared as public or private without affecting its
meaning
Usually it has object as arguments
5. Member functions of one class can be friend functions of another
class. In such cases, they are designed using the scope resolution
operator.
We can also declared the class as a friend class.