2. Friend Function
A type of function that is allowed to access the
private and protected members of a particular
class from outside the class is called friend
function. Normally, the private and protected
members of any class cannot be accessed
from outside the class. In some cases a
program may require to access these
members. The use of friend functions allows
the user to access these members.
3. A function that is declared in a class with
friend keyword becomes the friend
function of that class. It enables that
function to access the private and
protected members of the class. Suppose
a friend function accepts two objects of
different classes as parameters. It has to
process the private data members of
these classes and then displays the
result.
4. It is not possible to perform the task
because a function that is not a member
of a class cannot access the private or
protected members of the class. The
problem can be solved by declaring that
function as friend function of both
classes. It will enable the function to
access the private and protected
members of both classes.
5. class B;
class A {
private: int a;
public: A() {
a = 10;
}
friend void show(A, B);
};
class B{
private: int b;
public: B() {
b = 20;
}
friend void show(A, B);
};
6. void show(A x, B y) {
int r;
r = x.a + y.b;
cout << “Sum of private values = ” << r;
}
void main()
{
A obj1;
B obj2;
show(obj1, obj2);
}
7. Friend Classes
A type of class all of whose member
functions are allowed to access the
private and protected members of a
particular class is called friend class.
Normally the private and protected
members of any class cannot be accessed
from outside the class.
8. In some cases a program may require to
access these members. The use of friend
classes allows a class to access these
members of another class. A class that is
declared in another class with friend
keyword become the friend class.
9. class A {
private: int a, b;
public: A() {
a = 10;
b = 20; }
friend class B;
};
class B{
public: void showA (A obj) {
cout << “Value of a” << obj.a; // a is member of clas A
}
void showB (A obj) {
cout << “Value of b” << obj.b; }
};
10. void main()
{
A x;
B y;
y.showA (x); // class A obj can use variable a
y.showB (x); // class A obj can use variable b
}