Object-Oriented Programming In C++: Friend Function
Submitted by PhoeniciansSy on Monday, September 22, 2014 - 09:22.
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:- // 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.
Add new comment
- 131 views