Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Friends  to  a  Class

The   concepts   of   encapsulation   and   data  hiding  dictate  that  non-member  functions should  not  be  able  to  access  an  object's  private  or  protected  data.  Any  attempt  by  a non-member  function  to  directly  access  these  data  members ( via  object )  will  result  in a  compile-time  error.  

There  are  situations  in  which  a  class  may  grant  friendship:



1)  To  a  non-member  function.

2)  To  a  particular  member  function  of  another  class.

3)  To  another  class ( all  member  functions  of  that  class  are  friend  functions ).



Since   a   friend   is   a  non-member  of  a  class,  it  is  not  affected  by  the  public, protected  or  private  section  in  which  they  are  declared  within  the  class  body.



For  example,

                                  class  A
                                  {
                                                           friend  class  B ;
                                               private :
                                                           int  v1 ;
                                                           int  v2 ;
                                  } ;

                                  class  B
                                  {
                                              public :
                                                           void  myfunc ( A &  obj )
                                                           {
                                                                       v1 + + ;     //  error

                                                                       obj.v1+ +;   // ok

                                                                       + +( obj.v2 ) ;  // ok
                                               
                                                           }
                                  } ;



A  friend  class  ( and  function )  has  the  right  to  access  the  data  members  through  the object  only,  and  not  directly.