CodesJava

Easy learning with example program codes

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
Posted in CPP   
Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki