Any Data Which Is Declared Under Private Visibility Mode Inside
Any Data Which Is Declared Under Private Visibility Mode Inside
Any data which is declared under private visibility mode inside a class is not accessible from outside the
class. A function which is not a member or an class can never access such private data. But there may be
some cases, where a programmer will need to access to the private data from non-member functions and
external classes. C++ offers some new mechanism in such cases.
A class can allow non-member functions and other classes to access its own private data, by making
them as friends. This documentation give two important points.
• Once a non-member function is declared as a friend, it can access the private data of the class
• similarly when a class is declared as a friend, the friend class can have access to the private data
of the class which made this a friend
Let's see a sample in this C++ tutorial for each of the above cases.
#include <iostream.h>
int Friend1(int x);
class friend_tutorial {
int data;
friend int Friend1(int x);
public:
friend_tutorial()
{
data = 5;
}
};
int Friend1(int x)
{
friend_tutorial F1;
return var1. data + x;
}
int main()
{
cout << "Added Result is "<< friend(4)<<endl;
}
Friend class:
Declaration of a friend class is also similar. Only thing is a class definition is slightly different.
Friend function:
This is a good way out given by C++ to avoid restrictions on private variables. But this should be used
with caution though. If all the functions and classes are declared as friends, then the concept of
encapsulation and data security will go for a toss.
That is why the concept of friend functions and classes should be used with proper judgment.