Friends can access private members of a class. : Friend « Class « C++






Friends can access private members of a class.

  
#include <iostream>

using std::cout;
using std::endl;

class Count {
   friend void setX( Count &, int ); 
public:
   Count() { x = 0; }                
   void print() const { cout << x << endl; }
private:
   int x;
}; 

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

int main()
{
   Count counter;

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








Related examples in the same category

1.Friend function DemoFriend function Demo
2.Make the inserter into a friend functionMake the inserter into a friend function
3.Define friend function for <<Define friend function for <<
4.friend class for each other
5.Use friend function to access the non-public member variable