Friend Function in C++

C++ Friend Function

A friend function in c++ is a function which is declared within a class and is defined outside the class. It does not require any scope resolution operator for defining . Friend Function can access private members of a class. It is declared by using keyword [friend].

The private members cannot be accessed from outside the class. i.e.… a non member function cannot have an access to the private data of a class. In C++ a non member function can access private by making the function friendly to a class.

Characteristic of Friend Function in C++:

1. It is not in the scope of the class to which it has been declared as friend.
2. Since it is not in the scope of the class, it cannot be called using the object of that class. It can be invoked like a normal function without the help of any object.
3. Unlike member functions, it cannot access the member names directly and has to use an object name and dot membership operator with each member name.
4. It can be declared either in the public or private part of a class without affecting its meaning.
5. Usually, it has the objects as arguments.

Example :

#include <iostream.h>
class Test
int x;
int y;
public :
Test(int a, int b);
friend int sum(Test s);
Test::Test(int a, int b)
x =a;
int sum(Test s)
int sum =0;
sum = s.x +s.y;
return 0;
int main()
Test obj(2,3);
int res = sum(obj);
cout<<”Sum = ”<<res;
return 0;

Leave a Comment

Your email address will not be published. Required fields are marked *