CPP Friend Function

A function is called a friend function if the keyword friend is used with that function. The protected and private data of a class can be accessed using the friend function in CPP, if the function is declared inside the body of that class.

Syntax:

class class_name

{

friend data_type function_name(arguments);

};

 

Example:

#include <iostream.h>  
using namespace std;  
class Student
{  
private:  
int grades;  
public:  
Student(): grades(0) { }  
friend int printGrades(Student);   
};  
int printGrades(Student s1)
{  
s1.grades += 8;  
return s1.grades;  
}  
int main()  
{  
Student s1;  
cout<<"Grade of Student: "<< printGrades(s1)<<endl;  
return 0;  
}

Output

Grade of Student: 8
Please follow and like us:
Content Protection by DMCA.com