Private members cannot have access to the private data of a class; however, there could be a situation where we would like two classes to share a particular function. In such a situation, C++ allows the common function to be made friendly with both the classes; thereby, allowing the function to access the private data of these classes. Such functions need not be a member of any of these classes. To make an outside function “friendly” to a class, we simply have to declare this function as a friend of the class, as shown below:
class ABC
{
------
------
public:
-----
-----
friend void XYZ(void); //declaration
};
Here, function XYZ
is a friend of class ABC
.
The function declaration should be preceded by the keyword friend
. The function is defined elsewhere in the program as a normal C++ function. The function definition will not use the keyword friend or scope operator ::
, but the function can be declared as a friend in any number of classes.
#include <iostream>using namespace std;class Dist {private:int m;friend int addf(Dist);public:Dist() : m(0) {}};int addf(Dist d){d.m += 5;return d.m;}int main() {Dist D;cout << "Distance: " << addf(D);return 0;}