Friend class in C++

Friend class in C++



  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class Shape{  
  5. private:  
  6.     int length;  
  7.     int width;  
  8.     int height;  
  9. public:  
  10.     Shape(int a,int b,int c){  
  11.         length=a;  
  12.         width=b;  
  13.         height=c;  
  14.     }  
  15.     friend class Area;///Friend class Area  
  16. };  
  17.   
  18. class Area{  
  19. public:  
  20.     void getArea(Shape obj){  
  21.         cout<<"Area: "<<obj.length*obj.width<<endl;   ///Since Area is friend of Shape, it can access private members of Shape.  
  22.     }  
  23. };  
  24.   
  25. int main()  
  26. {  
  27.     Shape shape(2,4,6);  
  28.     Area area;  
  29.     area.getArea(shape);  
  30.     return 0;  
  31. }  
Share:

0 Comments:

Post a Comment