// friends can access private members, but non-friend/non-member functions // can not access private data of a class #include class Count { friend void setX(Count &, int); // friend declaration public: Count() {x = 0;} // constructor void print() const { cout << x << endl; } private: int x; // private data member }; void setX(Count &c, int value) { c.x = value; // legal if setX is a friend of class Count } // void cannotSetX(Count &c, int value) { // c.x = value; // error: 'Count::x' is not accessible // } main( ) { Count object; cout << "friend function can access private data member" << endl; cout << "object.x after initilized: "; object.print(); cout << "object.x after friend function setX is called: "; setX(object, 5); // set x with a friend object.print(); cout << endl; cout << "include the non-friend function and see what happens" << endl; // cout << "non-friend can not access private data member" << endl; // cannotSetX(object, 10); // cannotSet is not a friend getchar(); return 0; }