2. Introduction
➢ If a function is defined as a friend function in C++, then
the protected and private data of a class can be accessed
using the function.
➢ By using the keyword friend compiler knows the given
function is a friend function.
➢ For accessing the data, the declaration of a friend
function should be done inside the body of a class
starting with the keyword friend.
3. Declaration of friend function
SYNTAX :
class className
{
… .. ….
friend returnType functionName
(arguments)
… .. ….
}
4. Characteristics of friend function
➢ The function definition does not use either the keyword friend or scope
resolution operator.
➢ A friend function is not in the scope of the class, in which it has been declared as
friend.
➢ It cannot be called using the object of that class.
➢ It can be invoked like a normal function without any object.
➢ Unlike member functions, it cannot use the member names directly.
➢ It can be declared in public or private part without affecting its meaning.
5. What’s the use of friend function?
Data hiding is a fundamental concept of object-oriented
programming. It restricts the access of private members
from outside of the class.
Similarly, protected members can only be accessed by
derived classes and are inaccessible from outside. For
example,
6. Example & Explanation
class MyClass
{
private:
int member 1 ;
};
int main()
{
MyClass obj;
// Error! Cannot access private
members.
obj.member 1=5;
}
Here we cannot access the
member 1. Since it is a
private member of the
class.Hence, to avoid this
we use “FRIEND
FUNCTONS”.It allow us to
access member functions
from outside the class.
7. EXAMPLE FOR
FRIEND
FUNCTION
CODING:
#include <iostream>
Using namespace std;
class Temperature
{
int celsius;
public:
Temperature( )
{
celsius=0
}
friend int temp(Temperature);
};
int temp(Temperature t)
{
t.celsius=40;
return t.celsius;
}
int main( )
{
Temperature tm;
cout <<”Temperature in celsius:”<<temp(tm)
return 0;
}
CODING ,OUTPUT AND
EXPLANATION
8. Output & Explanation
*OUTPUT:
Temperature in celsius : 40
*EXPLANATION:
Here we declared a function 'temp' as the friend function of the class
'Temperature'. In the friend function, we directly accessed the private member celsius
of the class 'Temperature'.When the first statement of the main function created an
object 'tm' of the class 'Temperature' thus calling its constructor and assigning a value
0 to its data member celsius.The second statement of the main function called the
function 'temp' which assigned a value 40 to celsius