You are on page 1of 2

DATE: 05-07-2021

Friend functions of the class are granted access to private and protected members of the class
in C++. They are defined outside the class’ scope. Friend functions are not member functions of
the class. So, what exactly is the friend function?

What is a Friend Function?


A friend function is a function that is specified outside a class.

What is a Friend Function in C++?


A friend function in C++ is defined as a function that can access private, protected and a public
member of a class.
The friend function is declared using the friend keyword inside the body of the class.

Friend Function Syntax:


1 class className {
2 ... .. ...
3 friend returnType functionName(arguments);
4 ... .. ...
}
5
By using the keyword, the ‘friend’ compiler knows that the given function is a friend function.
We declare friend function inside the body of a class, starting with the keyword friend to access
the data. We use them when we need to operate between two different classes at the same time.

Declaration of a friend function in C++


1 class class_name
2 {
3 friend data_type function_name(arguments/s); //syntax of friend function.
4 };

In the above declaration, the keyword friend precedes the function. We can define the friend
function anywhere in the program like a normal C++ function. A class’s function definition
does not use either the keyword friend or scope resolution operator (: 🙂.
Friend function is called as function_name(class_name) and member function is called as
class_name. function_name.

Characteristics of Friend Function in C++


 The function is not in the ‘scope’ of the class to which it has been declared a friend.
 It cannot be invoked using the object as it is not in the scope of that class.
 We can invoke it like any normal function of the class.
 Friend functions have objects as arguments.
 It cannot access the member names directly and has to use dot membership operator
and use an object name with the member name.
 We can declare it either in the ‘public’ or the ‘private’ part.

/*PROGRAM FOR FRIEND FUNCTION*/


# include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box ()
{
length=0;
}
friend int printLength (Box); //friend function
};

int printLength (Box t)


{
t.length = t.length + 10;
return t.length;
}
main ()
{
Box b;
cout <<"Length of box = "<<printLength(b)<<endl;
}

You might also like