Friend function

Friend function:

It is a function of a class that defined outside the class’ scope but it has the right to access the private and protected members of the class. Even if the prototypes of friend functions appear in the class definition, friends are not member functions.
A friend may be a function, function template, or member function, or a class or class template, in which case the whole class and all of its members are friends.
Syntax:-
Friend returntype functionname(datatype of arguments)

Example 1
#include<iostream.h>

class Box

{

double width1;

public: friend void showWidth( Box box );

void setWidth1( double wid );

};

// Member function definition

void Box::setWidth1( double wid )

{

Width1 = wid;

} // Note: showWidth() is not a member function of any class.

void showWidth( Box box )

{

/* Because showWidth() is a friend of Box, it can directly access any member of given class */

cout << “Width of the box is: ” << box.width <<endl;

} // Main function for the program

int main( )

{

Box box1; // set box width with member function box1.setWidth1(10.0); // Use friend function to show the wdith.

showWidth( box1 ); return 0;

}

Output
Width of the box is :10.
Example 2:Simple Program for Friend Function Using C++ Programming
#include<iostream.h>

#include<conio.h>

class basec

{

int vall1,vall2;

public: void get1()

{

cout<<“Enter two values:”; cin>>vall1>>vall2;

}

friend float mean(basec ob);

};

float mean(basec ob)

{

return float(ob.vall1+ob.vall2)/2;

}

void main()

{

clrscr();

basec obj;

obj.get1();

cout<<“\n Mean value is : “<<mean(obj);

getch();

}

Output
Enter two values: 45

67

Mean value is :45

Leave a Reply

Your email address will not be published. Required fields are marked *