Thursday 29 May 2014

Friend Class


                Friend class is also used to access private members of the class in another class. Here we use forward declaration of class.

#include<conio.h>
#include<iostream>
using namespace std;
class square;//Forward declaration of class

class rectangle
{
                int hieght;
                int width;
                public:
                                rectangle(){hieght=0,width=0;}
                                rectangle(int a, int b){hieght=a,width=b;}
                                void convert(square s);// class sqaure is called in the rectangle class.
                                int area()
                                {
                                return hieght*width;
                                }
};

class square
{
                friend class rectangle; //declaring rectangle as a friend class
                int side;
                public:
                                square(int a){side=a;}
                               
};
void rectangle::convert(square s)
{
                hieght=s.side;
                width=s.side;
}

int main()
{
                rectangle rect;
                square sqr(4);
                rect.convert(sqr);
               
                cout<<"area of square :"<<rect.area();
                getch();
                return 0;
               

No comments:

Post a Comment