My 2 Cents What Is Friend Function?

Swati Mishra

Content Writer
If a member of class is private or protected, functions cannot access the non-public means private or protected members of class. So sometimes it becomes problem for the programmer. In order to access the non-public member of a class, for solving this problem C++ provide the Friend keyword.

Any non-member function may be declaring a friend by a class. In this situation the function may directly access the private member attributes and the method of a class.
Syntax

Class
{
Friend function ();
Private:

};
 

Doominic anderson

White Belt
Friend function is a special function in C++ programming language, it is not the member function of that class but it has the authority to access all the members of that class. Private members of the class are only accessed by the object of that class but a function which is named as friend function can access the private as well as protected members of the class which is not defined within the scope of that class.
 

Swati Mishra

Content Writer
Friend function is a special function in C++ programming language, it is not the member function of that class but it has the authority to access all the members of that class. Private members of the class are only accessed by the object of that class but a function which is named as friend function can access the private as well as protected members of the class which is not defined within the scope of that class.
absolutely correct @ doominic anderson Friend function specially use for the non- public member that is the private and protected access specifier.
 

VIVEK KUMAR

White Belt
Example of friend function -
For finding the mean value of a given number by using friend function.
Code:
#include<iostream.h>
class  base			// Base class
{
	int value1,value2; 
   public:
	void get()
	{
	   cout<<"Enter two values:";
	   cin>>value1>>vauel2;
	}
	friend float mean(base object); // friend function
};
float mean(base ob)
{
   return float(ob.val1+ob.val2)/2; // Formula of mean value calculation.
}
void main()  // main or driving function
{
	clrscr();
	base object;
	object.get();
	cout<<"Mean value is : "<<mean(object);
	getch();
}
 
Top