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
Here is an example
/* Onur AKTAS – alonon.net
* 15/12/2008
* Friend Functions
*/
#include <iostream>
using namespace std;
class INTEGER
{
int num; // private variable
public:
INTEGER(int n=0) {num = n;} // constructor to assign n to num
friend void add(INTEGER &x,INTEGER &y); // this is friend function, it is not a member function, and can not write in class
};
void add (INTEGER &x,INTEGER &y) // do not write friend at the begining
{
cout<<"Addition is: "<<x.num+y.num<<endl; // plus x’s num with y’s num
}
int main ()
{
INTEGER x(5);
INTEGER y(6);
add(x,y);
return 0;
}
Related posts
Recent Comments