Any data which is declared private inside a class is not accessible from outside the class. A function which is not a member or an external class can never access such private data. But there may be some cases, where a programmer will need need access to the private data from non-member functions and external classes. C++ offers some exceptions 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 part of C++ tutorial essentially gives 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
C++ Tutorial - Friend function sample:
#include//Declaration of the function to be made as friend for the C++ Tutorial sample
int AddToFriend(int x);
class CPP_Tutorial
{
int private_data;
friend int AddToFriend(int x);
public:
CPP_Tutorial()
{
private_data = 5;
}
};
int AddToFriend(int x)
{
CPP_Tutorial var1;
return var1.private_data + x;
}
int main()
{
cout << "Added Result for this C++ tutorial: "<< AddToFriend(4)<
The output of the above C++ Tutorial sample will be
Added Result for this C++ tutorial: 9
C++ tutorial - friend class:
Declaration of a friend class is also similar. Only thing is a class definition is slightly different.C++ Tutorial - Friend function:
#include <>
class CPP_Tutorial
{
int private_data;
friend class friendclass;
public:
CPP_Tutorial()
{
private_data = 5;
}
};
class friendclass
{
public:
int subtractfrom(int x)
{
CPP_Tutorial var2;
return var2.private_data - x;
}
};
int main()
{
friendclass var3;
cout << "Added Result for this C++ tutorial: "<<>
}
Subtracted Result for this C++ tutorial: 3
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.
No comments:
Post a Comment