CP2001 Data Structures and Algorithms
More Basic Concepts in C++

Page 6 of 6

prev
Back
up
Start

Friend Functions

Chpt 7.3
A friend function of a class is a non-member function which can gain access to the private (and protected) section of the class.

For example,

	class A
	{
	  private:
		int val;
		...
	  public:
		...
		void wonderland();  //member function
		friend void alice();  //non-member function
		...
	};
allows the non-member function alice() to access class A's private members (eg, val).

Note that, since alice() is not a member function of class A, it is

Hence the advantage to using friend functions.

You can also make all of a class's member functions to be friends of another class:

	class X
	{
	  ...
	  friend class Y;  // make all of y's member functions friends of X
	  ...
	};
That is, allow all member functions in class Y to access the private members of class X.

We shall use this at a later stage.

Advantages of friend functions:

Note: Use friend functions sparingly - private members should stay private (as much as possible!).


Copyright © 1998 Olivier de Vel. All rights reserved.
prev
Back
up
Start