Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 9

Friend Functions

and
Friend Classes

Friend Functions & Friend Classes


Private

data of a class is accessible only to


member functions.
We know a private member cannot be accessed
from outside the class. A non member function
cannot have access to private data of a class
But a Friend function can access private data of a
class.
Non member functions can access private
members of a class using friend functions or friend
classes.
It permits a function or all functions of another class
to access a different classs private members.

Friend function
Function

declaration is prefixed by keyword

friend.
The function definition does not use either
the keyword friend or the scope resolution
operator ::.

To declare a friend function


class ABC
{
: :
: :
public :
friend void xyz(void); //declaration
};
Functions declared with keyword friend
are called as friend functions.

Friend function
It

cannot be called using the object of the class


It can be invoked like a normal function
A friend function although , not a member
function has full access to the private members
of the class
But it cannot access Class members directly. It
uses object and dot operator with each member
name to access both private and public
members.
A function can be friend to multiple classes.

Bridging classes with friends


If there is a situation where a function is to

be shared between two classes .i.e function


operating on objects of two different classes.
Friend functions can be used to bridge two
classes

Eg
#include<iostream.h>
Class ABC;
Class XYZ
{ int x;
public :
void setvalue(int i) { x=i;}
friend void max(XYZ, ABC);
};
Class ABC
{ int a;
public :
void setvalue(int i) { a=i;}
friend void max(XYZ, ABC);
};

Void max(XYZ m, ABC n)


{if(m.x >= n.a)
cout<<m.x;
else
cout<<n.a;
}
int main()
{ ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max(xyz, abc);
retur 0;
}

Friend Classes
The

Friend Keyword allows a function or


all functions of a class to manipulate
private members of another class.
To declare a class as a friend, use
keyword friend with class name and
declare it in the class whose private date
we want to manipulate.

You might also like