Mega Code Archive

 
Categories / C++ / Class
 

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; }