Thursday, 19 January 2012

Program Of Friend Class In C++


#include<iostream.h>
#include<conio.h>
class demo
{
private:
int a,b;
public:
demo(int x,int y)
{
a=x;
b=y;
}
 friend class semo;
};
class semo
{
public:

void display1(demo d1)
{
cout<<"a="<<d1.a;
}
void display2(demo d2)
{
cout<<"\n b="<<d2.b;
}
};
main()
{
clrscr();
demo t(9,3);
semo s;
s.display1(t);
s.display2(t);
getch();
}

........................................................................................................................





A friend class in C++, can access the "private" and "protected" members of the class in which it is declared as a friend. On declaration of friend clas
 all member function of the friend class become friend of the class in which the friend class was declared. Friend status is not inherited; every friendship has to be explicitly declared. Friend classes can help in improving encapsulation if used wisely.



Classes are declared as friends within the definition of the class to whom access is to be given; this prevents a class from giving itself access to another's protected members, which enforces encapsulation. The friend class has the same level of access irrespective of whether the friend declaration appears in either the public, protected or private sections of the class definition. Friend status is granted by using the classkeyword.

No comments:

Post a Comment