Thursday, August 31, 2017

Friend function in c++

A friend function is a function defined outside of C++ class. But it has the right to access all private and protected members of the class. Prototypes for friend functions appear in the class definition. The friends are not member functions.
Use of Friend function in C++
#include <iostream>
using namespace std;

class Student {
   double percen;
public:
   friend void printPercen( Student s1 );
   void setPercen( double per );
};

void Student::setPercen( double per ) {
   percen = per;
}

// printPercen() is not a member function of any class.
void printPercen( Student s1 ) {

/*printPercen() is a friend of Student class,hence can access any member of Student class*/

   cout << "Percentage of s1: " << s1.percen;
}

int main( ) {
   Student s1;
   s1.setPercen(90.5);
   // Use friend function to print the percentage.
   printPercen( s1 );
   return 0;
}

Output of program:

Percentage of s1: 90.5

No comments:

Post a Comment