Object-Oriented Programming In C++: Friend Function

Friend Function:

Is a function that: 1. is not a member of a class. 2. has access to the class's private and protected members. 3. is considered as a normal external function that is given special access privileges. 4. is not in the class's scope. 5. is not called using the member-selection operators (. and –>) unless they are members of another class. 6. is declared by the class that is granting access. We can define a friend function anywhere in the class declaration. It is not affected by the access control keywords. For Example:
  1. // Modified Count class
  2. class Count
  3. {
  4.     friend void setX( Count &, int ); // friend declaration
  5.     public:
  6.        Count() { x = 0; }  // constructor
  7.        void print() const { cout << x << endl; }  // output
  8.     private:
  9.        int x; // data member
  10. };
- setX() is a friend function of Count class, it has access to the class's private and protected members. - We can implement setX() function outside Count class as a normal function, as follow:
  1. // Can modify private data of Count because
  2. // setX is declared as a friend function of Count
  3. void setX( Count &c, int val )
  4. {
  5.     c.x = val;  // legal: setX is a friend of Count
  6. }
We can test it in the main function as follow:
  1. int main()
  2. {
  3.    Count counter;
  4.  
  5.    cout << "counter.x after instantiation: ";
  6.    counter.print();
  7.    cout << "counter.x after call tosetX friend function: ";
  8.  
  9.    setX( counter, 8 );  // set x with a friend
  10.    counter.print();
  11.    return 0;
  12. }
The output:
counter.x after instantiation: 0 counter.x after call to setX friend function: 8
We will re-implement the previous example without using a friend function as follow:
  1. // Modified Count class
  2. class Count
  3. {
  4.    public:
  5.       Count() { x = 0; }  // constructor
  6.       void print() const { cout << x << endl; }  // output
  7.    private:
  8.       int x; // data member
  9. };
  10.  
  11. // Function tries to modifyprivate data of Count,
  12. // but cannot because it isnot a friend of Count.
  13. void cannotSetX( Count &c, int val )
  14. {
  15.     c.x = val;  // ERROR: 'Count::x'is not accessible
  16. }
  17.  
  18. int main()
  19. {
  20.     Count counter;
  21.  
  22.     cannotSetX( counter, 3 ); // cannotSetX is not a friend
  23.     return 0;
  24. }
The output with errors:
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.
Tags

Add new comment