Friend function in C++

Friend function in C++



  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class Shape;///Create forward reference of Class Shape  
  5.   
  6. class Area{///Create the class Area which member function be friend of class Shape  
  7. public:  
  8.     void getArea(Shape obj);  
  9. };  
  10.   
  11. class Shape{///Create class Shape  
  12. private:  
  13.     int length;  
  14.     int width;  
  15.     int height;  
  16. public:  
  17.     Shape(int a,int b,int c){  
  18.         length=a;  
  19.         width=b;  
  20.         height=c;  
  21.     }  
  22.     friend void Area::getArea(Shape obj);  
  23. };  
  24. ///Define friend function  
  25. void Area::getArea(Shape obj){  
  26.     cout<<"Area: "<<obj.length*obj.width<<endl;  
  27. }  
  28.   
  29. int main()  
  30. {  
  31.     Shape shape(3,4,5);  
  32.     Area area;  
  33.     area.getArea(shape);  
  34.     return 0;  
  35. }  
Share:

0 Comments:

Post a Comment