Вы находитесь на странице: 1из 10

Friend of a Class

Friend Functions

Friend Functions

The private members cannot be accessed from outside the class. A non-member function cannot have an access to the private data of the class. To allows the common function to be made friendly with both the classes, thereby allowing the function to have access to the private data of these classes.

Syntax
class abc { .. public: .. friend void xyz(void); };

//declaration

Important???

The function that are declared with the keyword friend are known as friend function. The function declaration should be preceded by the keyword friend. The function defines does not use either the keyword friend or the scope resolution operator (::). A function can declared as a friend in any number of classes.

Characteristics

It is not in the scope of the class to which it has been declared as friend. Since, it is not in the scope of the class, it cannot be called using the object of that class. It can be declared either in the public or in the private part of the class. It has the objects as arguments. It cannot access the member names directly & has to use an object name & dot membership operator with beach member name (abc.r).

Example: #include<iostream.h> #include<conio.h. class abc { int a, b; public: void getdata() { a=25; b=30; } friend float mean(abc s); }; float mean(abc s) { return float(s.a+s.b)/2.0; }

Contd
int main() { abc x; x.getdata(); cout<< Mean Value: << mean(x); return 0; } OUTPUT:Mean Value: 27.5

Friend function of Another Class


Member functions of one class can be friend functions of another class. Syntax : class a { . int fun1(); //member function of a . };

Contd
class b { . . friend int a :: fun1(); //fun1() of a class . //is friend of b class }; Note: -The function fun1() is a member of class a & friend of class b.

Thanks!!!

Вам также может понравиться