270 likes | 976 Views
Friend Functions and Friend Classes. Friend to a Class. In some instances the condition of information hiding needs to be relaxed. Using friend mechanism nonmembers of the class can access nonpublic members of class.
E N D
Friend to a Class • In some instances the condition of information hiding needs to be relaxed. • Using friend mechanism nonmembers of the class canaccess nonpublic members of class. • Declaring friend inside the class definition “who can access my private implementation?” • class controls which code has access to its members. • Can declare a global function as a friend, and also a member function of another structure, or even an entire structure.
friendFunctions and friend Classes • friend function • Defined outside class’s scope • Right to access non-public members • Declaring friends • Function • Precede function prototype with keyword friend • All member functions of class ClassTwo as friends of class ClassOne • Place declaration of form friend class ClassTwo; in ClassOne definition
friendFunctions and friend Classes • Properties of friendship • Friendship granted, not taken • Class Bfriend of class A • Class A must explicitly declare class Bfriend • Not symmetric • Class Bfriend of class A • Class A not necessarily friend of class B • Not transitive • Class Afriend of class B • Class Bfriend of class C • Class A not necessarily friend of Class C
Note: Because a friend function is not a member function: • definition not qualified with class name and scope operator (::) • receives the object on which it can operate. • uses the dot operator to access the data members.
Precede function prototype with keyword friend. Example class Count { friend void SetX(Count, int); public: Count() { x = 0 } void print(void) { cout<<x; } private: int x; }; void SetX(Count c, int val) { c.x = val; } void main(void) { Count cnt; SetX(cnt, 20); cnt.print(); }
Another Example class classA { friend class classB; private: int data; }; class classB { public: void displaydata_of_classA(classA aObj) { cout<<aObj.data; } void setdata_of_classA(classA aObj, int d) { aObj.data=d; } }; void main(void) { classA a; classB b; b.setdata_of_classA(a,25); b.displaydata_of_classA(a); }