FRIEND FUNCTION & FRIEND
CLASS

Abhishek Wadhwa
Bharati Vidyapeeth‟s Institute of Computer Application
Management(BVICAM)
Who is a Friend?




A friend is one who has access to all your
“PRIVATE” stuff
What is Friend Function?
   A non member function

   Has access to all the Private and Protected
    Members of a class
How is it different from normal
function?
   A member is access “through” the object

Ex     :   sample object;
           object.getdata();

   Whereas A Friend function requires object to
    be passed by value or by reference as a
    parameter

Ex     :     void getdata(sample object);
Code Snippet:
class demo
{
int x;
public:
demo(int xx)
{
x=xx;
}
friend void display(demo);   //Declaration inside the class
};

void display(demo dd1)       //Definition outside the class
{
cout<<dd1.x;
}
What are its Disadvantages?
   Violates Data Hiding

   Violates encapsulation
Friend class
   Provides the same feature as that of Friend
    Fn.

   Allows „member fn” of one class to friend of
    other class

   i.e. the private member of the class will be
    accessible to the friend class
Code snippet:
class xxx
{
int x;
public:
xxx(int xx)
{
x=xx;
}
friend class yyy;
};
class yyy
{
public:
void f1(xxx obj)
{cout<<“x=”<<obj.x;}
};
Thank You
www.programming90.blogspot.in


   www.ipnotes.blogspot.in
      Abhishek wadhwa

Friend function & friend class

  • 1.
    FRIEND FUNCTION &FRIEND CLASS Abhishek Wadhwa Bharati Vidyapeeth‟s Institute of Computer Application Management(BVICAM)
  • 2.
    Who is aFriend? A friend is one who has access to all your “PRIVATE” stuff
  • 3.
    What is FriendFunction?  A non member function  Has access to all the Private and Protected Members of a class
  • 4.
    How is itdifferent from normal function?  A member is access “through” the object Ex : sample object; object.getdata();  Whereas A Friend function requires object to be passed by value or by reference as a parameter Ex : void getdata(sample object);
  • 5.
    Code Snippet: class demo { intx; public: demo(int xx) { x=xx; } friend void display(demo); //Declaration inside the class }; void display(demo dd1) //Definition outside the class { cout<<dd1.x; }
  • 6.
    What are itsDisadvantages?  Violates Data Hiding  Violates encapsulation
  • 7.
    Friend class  Provides the same feature as that of Friend Fn.  Allows „member fn” of one class to friend of other class  i.e. the private member of the class will be accessible to the friend class
  • 8.
    Code snippet: class xxx { intx; public: xxx(int xx) { x=xx; } friend class yyy; }; class yyy { public: void f1(xxx obj) {cout<<“x=”<<obj.x;} };
  • 9.
    Thank You www.programming90.blogspot.in www.ipnotes.blogspot.in Abhishek wadhwa