Modifying a Class’s private Data with a Friend Function

Figure 9.22 is a mechanical example in which we define friend function setX to set the private data member x of class Count. As a convention, we place the friend declaration (line 9) first in the class definition, even before public member functions are declared. Again, this friend declaration can appear anywhere in the class.

 1   //Fig. 9.22: fig09_22.cpp 2   // Friends can access private members of a class. 3   #include <iostream> 4   using namespace std; 5  6   // Count class definition 7   class Count 8   { 9      friend void setX( Count &, int ); // friend declaration 10   public:11      // constructor12      Count()13         : x( 0 ) // initialize x ...

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.