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

Friend Function &

Friend Class

V.Radhesyam
'friend' function/Class
• A 'friend' function has access to all 'private'
members of the class for which it is a 'friend'.

• A friend class has access to all 'private' members


of the class for which it is a 'friend'.

• Friend function is non-member function of a


Class

• To declare a 'friend' function, include its


prototype within the class, preceding it with the
C++ keyword 'friend'.
Friend Function
class base float mean(base ob)
{ {
return float(ob.val1 + ob.val2) / 2;
int val1, val2;
}
public:
void get() void main() {
{ clrscr();
cout << "Enter two values:"; base obj;
obj.get();
cin >> val1>>val2;
cout << "\n Mean value is : " <<
} mean(obj);
friend float mean(base ob); getch();
}; }
Friend Function with two classes example
class beta; class beta int frifun(alpha a,beta b)
class alpha { {
{ private:
private: int data; return(a.data+b.data);
int data; public: }
public: beta()
alpha() {
{ data=7; Void main()
data=3; } {
} friend int alpha aa;
friend int frifun(alpha ,beta ); beta bb;
frifun(alpha,beta); }; cout<<frifun(aa,bb);
}; }
Friend Class
class Rectangle class Square void main()
{ {
{
int L,B; int S;
Rectangle R;
public:
Square S;
Square()
public: S.Display(R);
{
Rectangle() S=5; }
{ }
L=10;
void Display(Rectangle Rect)
B=20; {
} cout<<"Length : "<<Rect.L;
cout<<"Breadth : "<<Rect.B;
friend class cout<<"Side : "<<S;
Square; }
}; };
Lab Assignments
1. Write a program to accept the student detail such as name and 3 different
marks by get_data() method and display the name and average of marks
using display() method. Define a friend class for calculating the average of
marks using the method mark_avg().

2. Write a C++ program to find the sum of two complex numbers using friend
functions.

3. Develop a C++ Program to Implement Friend Class for Adding two


Numbers where class sum is declared as friend of other class used to read
values

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