Saturday, February 2, 2013

Friend Class in C++


Friend Class:
A friend class in C++ can access the private and protected members of the class in which it is declared as friend.
Friend status is not inherited; every friendship has to explicitly declare. Friend classes can help in improving encapsulation.
A friend class has following characteristics:
1.     It allows sharing private and protected member by a non-member function.
2.     It provides function with data which is not normally used by the class.

#include<iostream.h>
class csqr;
class crect;
{
            int width,height;
            public:
                        int area()
                        {
                                    area(width*height);
                        }
                        void convert(csqr);
};



class csqr
{
            int side;
            public:
                        void setvalue(int a)
                        {
                                    Side=a;
                        }
                        friend class crect;
};
void crect::convert(csqr obj)
{
            width=obj.side;
            height=obj.side;
}
void main()
{
            csqr sqr;
            crect rect;
            sqr.setvalue(10);
            rect.convert(sqr);
            cout<<rect.area();
}
Operator overloading with friend function:
class array
{
            int a[3];
            public:
            friend ostream & operator<<(ostream &,array &) ;
            friend istream & operator>>(istream &,array &) ;
};
ostream & operator<<(ostream &dout,array &obj)
{
            for(int i=0;i<3;i++)
                        dout<<obj.a[i];
            return dout;
}
istream & operator>>(istream &din,array &obj)
{
            for(int i=0;i<3;i++)
                        din>>obj.a[i];
            return din;
}
void main()
{
            array show;
            clrscr();
            cin>>show;
            cout<<show;
            getch();
}

0 comments:

Post a Comment

Powered by Blogger.