code for friend class

Discussion in 'C++' started by Fatima Khan, Feb 25, 2010.

  1. Fatima Khan

    Fatima Khan New Member

    Joined:
    Feb 20, 2010
    Messages:
    27
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Pakistan
    what should be the code sketch for friendship of two classes.......:worried:
     
  2. vivekraj

    vivekraj New Member

    Joined:
    Feb 23, 2010
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    We can declare function or class as friend.The friend function can access the private and protected members of that class.

    we can also define a class as friend of another one, granting that first class access to the protected and private members of the second one.

    Refer the following example.

    Code:
    // friend class
    #include <iostream>
    using namespace std;
    
    class CSquare;
    
    class CRectangle {
        int width, height;
      public:
        int area ()
          {return (width * height);}
        void convert (CSquare a);
    };
    
    class CSquare {
      private:
        int side;
      public:
        void set_side (int a)
          {side=a;}
        friend class CRectangle;
    };
    
    void CRectangle::convert (CSquare a) {
      width = a.side;
      height = a.side;
    }
      
    int main () {
      CSquare sqr;
      CRectangle rect;
      sqr.set_side(4);
      rect.convert(sqr);
      cout << rect.area();
      return 0;
    }
    In this example, we have declared CRectangle as a friend of CSquare so that CRectangle member functions could have access to the protected and private members of CSquare, more concretely to CSquare::side, which describes the side width of the square.

    You may also see something new at the beginning of the program: an empty declaration of class CSquare. This is necessary because within the declaration of CRectangle we refer to CSquare (as a parameter in convert()). The definition of CSquare is included later, so if we did not include a previous empty declaration for CSquare this class would not be visible from within the definition of CRectangle.

    Consider that friendships are not corresponded if we do not explicitly specify so. In our example, CRectangle is considered as a friend class by CSquare, but CRectangle does not consider CSquare to be a friend, so CRectangle can access the protected and private members of CSquare but not the reverse way. Of course, we could have declared also CSquare as friend of CRectangle if we wanted to.

    Another property of friendships is that they are not transitive: The friend of a friend is not considered to be a friend unless explicitly specified.

     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice