fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Box {
  6. double width;
  7.  
  8. public:
  9. friend void printWidth( Box box );
  10. void setWidth( double wid );
  11. };
  12.  
  13. // Member function definition
  14. void Box::setWidth( double wid ) {
  15. width = wid;
  16. }
  17.  
  18. // Note: printWidth() is not a member function of any class.
  19. void printWidth( Box box ) {
  20. /* Because printWidth() is a friend of Box, it can
  21.   directly access any member of this class */
  22. cout << "Width of box : " << box.width <<endl;
  23. }
  24.  
  25. // Main function for the program
  26. int main() {
  27. Box box;
  28.  
  29. // set box width without member function
  30. box.setWidth(10.0);
  31.  
  32. // Use friend function to print the wdith.
  33. printWidth( box );
  34.  
  35. return 0;
  36. }
Success #stdin #stdout 0.01s 5472KB
stdin
Standard input is empty
stdout
Width of box : 10