Wednesday, November 27, 2013

Friend functions

Private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not affect friends,

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

Friends are functions or classes declared with the friend keyword.
                          If we want to declare an external function as friend of a class, thus allowing this function to have access to the private and protected members of this class, we do it by declaring a prototype of this external function within the class, and preceding it with the keyword friend: 

#include <iostream>
 
 
class Student
{
   double id;
public:
   friend void printid( Student Student );
   void setId( double wid );
};

// Member function definition
void  Student ::setId( double wid )
{
    id = wid;
}

// Note: printId() is not a member function of any class.
void printId(  Student  student )
{
   /* Because setid() is a friend of Student, it can
    directly access any member of this class */
   cout << "Id of student : " << student .id <<endl;
}
 
// Main function for the program
int main( )
{
    Student  student ;
 
   // set student id without member function
   student .setId(10.0);
   
   // Use friend function to print the wdith.
   printId( student );
 
   return 0;
}

No comments:

Post a Comment