Friend Function -- Example :
Friend Function -- Example #define size 50
class student{ char *name; public: student(char *ip) {name = new char[size]; strcpy(name, ip);} print() {cout << "Name: " << name << endl;}
//friend function friend void dangerous_fn(student&); };
Friend Function -- Example :
Friend Function -- Example void dangerous_fn(student &s) {strcpy(s.name, "DANGER");}
main(){ student s1("John"); s1.print(); dangerous_fn(s1); s1.print();}
OUTPUT WILL BE: Name: John Name: DANGER
Friend Classes -- Danger!?:
Friend Classes -- Danger!? Not Directly Associated with the Class
All the Member Functions of the Friend Class Can Access Non-Public Data Members of the Original Class
Can be Friend of More than One Classes
Violation of Encapsulation
SHOULD BE USED ONLY WHEN REQUIRED
Friend Class -- Example:
Friend Class -- Example #define size 50
class student{ char *name; public: student(char *ip) {name = new char[size]; strcpy(name, ip);} print() {cout << "Name: " << name << endl;}
//friend class friend class dummy; };
Friend Class -- Example:
Friend Class -- Example class dummy{ //Friend Class public: void danger_member_fn(student &s) {strcpy(s.name, "FRIEND or FOE?");} };
main(){ student s("John"); s.print(); dummy risk; risk.danger_member_fn(s); s.print();}
OUTPUT WILL BE: Name: John Name: FRIEND or FOE?
Acknowledgements:
Acknowledgements These slides were originally prepared by Rajeev Raje, modified by Dale Roberts.