Sunday 29 March 2015

Friend Class

Friend functions permit an exception to the rules of data encapsulation. The friend keyword allows a function, or all the functions of another class to manipulate the private members of the original class. The syntax of declaring friend class is shown as follows:

Friend class class-name;

Sample Program

#include <iostream.h>
class boyd
{
int income1;
int income2;
public:
void setdata(int in1, int in2)
{
income1 = in1;
income2 = in2;
}
friend class girl;
};
class girl
{
int income;
public:
int girfunc(boy b1)
{
return b1.income1+b1.income2;
}
void setdata(int in)
{
income = in;
}
void show(void)
{
boy b1;
b1.setdata(100,200);
cout<<”Boy’s income1 in show() “<<b1.income1<<endl;
cout<<”Girl’s income in show() “<<income<<endl;
}
};
void main()
{
boy b1;
girl g1;
b1.setdata(500,1000);
g1.setdata(300);
cout<<”Boy b1 total income “<<g1.girlfunc(b1)<<endl;
g1.show();
}

The statement in the class boy

Friend class girl;

Declares that all the member functions of the class girl are friend functions of class boy but not the other way. The objects of the class girl can access all the members of the class boy irrespective of their access  privileges.


No comments:

Post a Comment