// Modified Count class class Count { friend void setX( Count &, int ); // friend declaration public: Count() { x = 0; } // constructor void print() const { cout << x << endl; } // output private: int x; // data member };
// Can modify private data of Count because // setX is declared as a friend function of Count 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 tosetX friend function: "; setX( counter, 8 ); // set x with a friend counter.print(); return 0; }
counter.x after instantiation: 0 counter.x after call to setX friend function: 8We will re-implement the previous example without using a friend function as follow:
// Modified Count class class Count { public: Count() { x = 0; } // constructor void print() const { cout << x << endl; } // output private: int x; // data member }; // Function tries to modifyprivate data of Count, // but cannot because it isnot a friend of Count. void cannotSetX( Count &c, int val ) { c.x = val; // ERROR: 'Count::x'is not accessible } int main() { Count counter; cannotSetX( counter, 3 ); // cannotSetX is not a friend return 0; }
Compiling... Fig07_06.cpp D:\books\2000\cpphtp3\examples\Ch07\Fig07_06\Fig07_06.cpp(22) : error C2248: 'x' : cannot access private member declared in class 'Count' D:\books\2000\cpphtp3\examples\Ch07\Fig07_06\ Fig07_06.cpp(15) : see declaration of 'x' Error executing cl.exe. test.exe -1error(s), 0 warning(s)Note: You can find the full source code of this example in code.zip file.