Private member function can’t be accessed from outside the class. That is a non-member function can’t access the private data of the class.
But with the friend function (non-member) we can access the private data of a class.
Friend function is needed in some situation where we need to share same function with more than one class.
To make an outside function friendly, We simply declare this function as a friend of the class.
class abc
{
public:
friend void xyz (parameters); //friend declaration
};
But with the friend function (non-member) we can access the private data of a class.
Friend function is needed in some situation where we need to share same function with more than one class.
To make an outside function friendly, We simply declare this function as a friend of the class.
class abc
{
public:
friend void xyz (parameters); //friend declaration
};
Friend function has some special characteristics:
- it is not in the scope of the class to which it is declared as a friend.
- Since it is not within the scope of the class so it can’t be called using the objects of that class.
- It can be invoked like a normal function without the help of any objects.
- Unlike member functions, it can’t access the member names directly.
- It can be declared either in public or private part of a class without affecting its meaning.
- Usually, it takes objects as arguments.
Tags:
Cpp