Classes Friends - PowerPoint PPT Presentation

1 / 7
About This Presentation
Title:

Classes Friends

Description:

Not Directly Associated with the Class. All the Member Functions of the Friend Class Can ... Can be Friend of More than One Classes. Violation of Encapsulation ... – PowerPoint PPT presentation

Number of Views:39
Avg rating:3.0/5.0
Slides: 8
Provided by: dalero
Category:

less

Transcript and Presenter's Notes

Title: Classes Friends


1
Classes Friends
Department of Computer and Information
Science,School of Science, IUPUI
CSCI 240
Dale Roberts, Lecturer Computer Science,
IUPUI E-mail droberts_at_cs.iupui.edu
2
Friend Function -- Example 
  • define size 50
  • class student char name public
    student(char ip) name new charsize
    strcpy(name, ip) print() cout ltlt "Name " ltlt
    name ltlt 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 charsize
    strcpy(name, ip) print() cout ltlt "Name " ltlt
    name ltlt 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.
Write a Comment
User Comments (0)
About PowerShow.com