Wednesday, February 16, 2011

Friend Functions and Friend Classes


Friend Functions and Friend Classes:
 A function is made to be friend of a class by using keyword friend before function declaration within class body. The friend function can access private data of the class for which it is declared as friend, although it is not member function of the class. The function definition doesn’t use either keyword friend or the scope resolution operator. A function can be declared as friend in any number of classes.
 
Characteristics of Friend Function:
Ø  Although friend function is not member function, it has full access to the private data of the class.
Ø  Friend Function is called like a normal function without the help of any object.
Ø  While using member data or functions, it uses object name and dot membership operator with each member name
Ø  Usually, it has objects as arguments.
Ø  Member function of one class can be friend function of another class. In such case, the member function is defined using the scope resolution operator. As
          class X {………….
                         int function1();
                     };
          class Y{…….
                       friend int X:: function1();
                   };

  Example for friend function:
  
class friendTest
   {
               float first,second;
               public:
               void get_value()
               {  cout<<"Enter two numbers"<<endl;
                  cin>>first>>second;    }
       friend float calculate_mean(friendTest s);
      };

 float calculate_mean(friendTest s)
       {     return((s.first+s.second)/2.0);     }

 void main()
   {
     friendTest  x;
      x.get_value();
      cout<<"Mean of these two numbers is "<<calculate_mean(x);
       }

A class can be declared as friend class of other such that all the member functions of one class are friend functions of later class. An example:
class X
   {
   float first,second;
    public:
    void get_value()
              {  cout<<"Enter two numbers"<<endl;
               cin>>first>>second;  }
      friend class Y;
       };

 class Y
        {  public:
            void display_data(X obj)
                  {cout<<"\nThe first number is: "<<obj.first<<"\nThe second number is: 
                                      <<obj.second;  }
            } ;

 void main()
   {  X x;
       Y y;
        x.get_value();
        y.display_data(x);  }

No comments:

Post a Comment