Can we write member function of one class as friend of another class ? How
A C++ friend functions are special functions which can access the private members of a class. They are considered to be a loophole in the Object Oriented Programming concepts, but logical use of them can make them useful in certain cases.
For instance: when it is not possible to implement some function, without making private members accessible in them. This situation arises mostly in case of operator overloading.
In the following example, the friend function print is a member of class TWO and accesses the private data members a and b of class ONE.
syntax:-
#include <iostream>
using namespace std;
//Must be known to TWO
//before declaration of ONE.
class ONE;
class TWO
{
public:
void print(ONE& x);
};
class ONE
{
int a, b;
friend void TWO::print(ONE& x);
public:
ONE() : a(1), b(2) { }
};
void TWO::print(ONE& x)
{
cout << "a is " << x.a << endl;
cout << "b is " << x.b << endl;
}
int main()
{
ONE xobj;
TWO yobj;
yobj.print(xobj);
}
Didn't get the answer.
Contact people of Talent-Object Oriented Programming directly by clicking here