70 likes | 83 Vues
Learn how to use friend functions and classes in C++ to access non-public data members of a class, the potential risks and violations of encapsulation, and when to use them. Includes examples and explanations.
E N D
Department of Computer and Information Science,School of Science, IUPUI ClassesFriends CSCI 240 Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu
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 • void dangerous_fn(student &s) {strcpy(s.name, "DANGER");} • main(){ student s1("John"); s1.print(); dangerous_fn(s1); s1.print();} • OUTPUT WILL BE: Name: JohnName: 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 • #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 • 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 • These slides were originally prepared by Rajeev Raje, modified by Dale Roberts.