3.17 Friend Functions


 

"C++ - Where only your friends can access your private parts"

 
 --Unknown, 1991

In C++ normal access control has the keywords:

  • private - only accessible within the class.

  • protected - only accessible within the class and its derived classes.

  • public - accessible anywhere.

A class can declare a function to be a friend, allowing that function to access private and protected members (friendship is granted! Not acquired.). For example:

  class SomeClass
  {
    private:
      int x;
      friend void someMethod(SomeClass &);
    
    public:
      // the interface
  };

  // This function is somewhere!
  void someMethod(SomeClass &a)
  {
    a.x = 5;    //allowed!
  }

It is important to note that someMethod() is not a member method of the class SomeClass. i.e. It does not have scope within the class SomeClass.

So if we tried:

        SomeClass b;
        b.someMethod();		

This is illegal, as someMethod() is not a member method of the SomeClass class (and it is not public).

Friend functions are useful as:

  • Friend function avoid adding unnecessary public methods to the interface.

  • Prevent states from having to be made public.

However, the overuse of friend functions can make the code very complex and hard to follow.

We can add all the methods of a class as friends of another:

  
  class A
  {
    private:
      int x;
      friend class B;
    public:
      //methods here
  };
		

Friendship is not inherited:

  
  class B
  {
    x(A &a)  //some method that is passed an object of A
    {
      a.x++;  //fine
    }
  };
  
  class C: public B   // class C is a child of B
  {
    y(A &a) //some method that is passed an object of A
    {
      a.x++;  //illegal
    }
  };
		

Friendship is not transitive:

  
  class AA
  {
    friend class BB;
  };
  
  class BB
  {
    friend class CC;
  };
  
  class CC
  {
    // Not a friend of AA
  };
	


These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way.
Comments