Showing posts with label accessing private data members of class. Show all posts
Showing posts with label accessing private data members of class. Show all posts

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;
               

Friend function

                Friend function is used to access private data members of the class. Friend is not a member function but it is declared in the class and defined outside the class. For friend class click on the link.


#include<conio.h>
#include<iostream>
using namespace std;
class avg
{
                private:
                        float a,b;
                public:
                                avg(){a=0.0,b=0.0;}
                                void get()
                                {
                                                cout<<"\n enter the value of a and b: ";
                                                cin>>a>>b;
                                }
                                friend float avrg(avg x); //friend function declaration.
};

float avrg(avg x) // friend definition.
{
                return (x.a+x.b)/2;
}


int main()
{
                avg A;
                A.get();
                cout<<"\n the average value of these two numbers is :"<<avrg(A);
                getch();
                return 0;

}