Wednesday, April 6, 2016

Friend Functions and Friend Classes in C++

We have been emphasizing that the private members cannot be accessed from outside the class. That is, a non-member function cannot have an access to the private data of a class. However, there could be a situation where we would like two classes to share a particular function. For example, consider a case where two classes, managerand scientist, have been defined. We would like to use a function income() to operate on the objects of both these classes. In such situations, C++ allows the common function to be made friendly with both the classes, thereby allowing the function to have access to the private data of these classes. Such a function need not be a member of any of these classes.
To make an outside class “friendly” to a class, we have to simply declare this function as a friend of the class as illustrated below:
The function declaration should be preceded by the keyword friend/ The function can de defined elsewhere in the program like a normal C++ function. The function definition does not use either the keyword friend or the scope operator ::. The functions that are declared with the keyword friend are known as friend function.
A friend function, although not a member function, has full access rights to the private members of the class.
A friend function possesses certain special characteristics s stated below:
  1. It is not in the scope of the class to which it has been declared as friend
  2. Since it is not in the scope of the class, it cannot be called using the object of that class. It can be invoked like a normal function without the help of any object
  3. Unlike member functions, it cannot access the member names directly and has to use an object name and dot membership operator with each member name (e.g., C.x)
  4. It can be declared either in the public or the private part of a class without affecting its meaning
  5. Usually, it has the objects as arguments
Program given below illustrates the use of a friend function.
The output of the above program would be:
Mean value = 32.5
In the given program:
  1. Note that the friend function accesses the class variables a and b by using the dot operator and the object passed to it
  2. The function call mean(x) passes the object x by value to the friend function
Now, also, member functions of one class can be friend functions of another class. In such cases, they are defined using the scope resolution operator as illustrated below:
In the above illustrative skeletal, the function fun1() is a member of class X and a friend of class Y.
We can also declare all the member functions of one class as the friend of another class. In such cases, the class is called as a friend class. This can be illustrated as follows:

0 comments:

Post a Comment