1 / 7

Friend Functions and Classes in C++: Exploring Encapsulation Violations

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.

rcolbert
Download Presentation

Friend Functions and Classes in C++: Exploring Encapsulation Violations

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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&); };

  3. 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

  4. 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

  5. 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; };

  6. 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?

  7. Acknowledgements • These slides were originally prepared by Rajeev Raje, modified by Dale Roberts.

More Related