Modifying a Class's private Data with a Friend Function, Friends can access private members of a class. - C++ Class

C++ examples for Class:Member Access

Description

Modifying a Class's private Data with a Friend Function, Friends can access private members of a class.

Demo Code

#include <iostream> 
using namespace std; 

class Count /*  w  ww  .  jav a2s.c om*/
{ 
   friend void setX( Count &, int ); // friend declaration 
public: 
   // constructor 
   Count() 
       : x( 0 ) // initialize x to 0 
   { 
       // empty body 
   } // end constructor Count 

   // output x 
   void print() const 
   { 
       cout << x << endl; 
   } // end function print 
private: 
   int x; // data member 
}; // end class Count 

void setX( Count &c, int val ) 
{ 
   c.x = val; // allowed because setX is a friend of Count 
}

int main() 
{ 
   Count counter; // create Count object 

   cout << "counter.x after instantiation: "; 
   counter.print(); 

   setX( counter, 8 ); // set x using a friend function 
   cout << "counter.x after call to setX friend function: "; 
   counter.print(); 
}

Result


Related Tutorials