1 / 8

Lab 3: Friend Function

Lab 3: Friend Function. Presented By: Nazia Hossain Lecturer, CSE Dept. Friend Function. Private can’t be accessed outside or Non-member functions can’t access private members or data. But friend function violates this rule!!!

marva
Download Presentation

Lab 3: Friend Function

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. Lab 3: Friend Function Presented By: Nazia Hossain Lecturer, CSE Dept

  2. Friend Function • Private can’t be accessed outside or Non-member functions can’t access private members or data. • But friend function violates this rule!!! • A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

  3. To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows: class Box { double width; public: double length; friend void printWidth( Box box ); void setWidth( double wid ); };

  4. To declare all member functions of class ClassTwo as friends of class ClassOne, place a following declaration in the definition of class ClassOne: • friend class ClassTwo;

  5. #include <iostream> using namespace std; class Box { double width; public: friend void printWidth( Box box ); void setWidth( double wid ); };

  6. // Member function definition void Box::setWidth( double wid ) { width = wid; } // Note: printWidth() is not a member function of any class. void printWidth( Box box ) { /* Because setWidth() is a friend of Box, it can directly access any member of this class */ cout << "Width of box : " << box.width <<endl; }

  7. // Main function for the program int main( ) { Box box; // set box width without member function box.setWidth(20.0); // Use friend function to print the wdith. printWidth( box ); return 0; }

  8. Problem Statement: • There will be a class named “library”. You will take input as “how many books do you want to borrow from library” using a member function of this class. This scope will be only within this “library” class. Again, there will be a friend function, (named whatever you want), which will display the number of the books you want to borrow.

More Related