// Rectangle is declared as a friend of Square so that Rectangle member functions // could have access to the protected and private members of Square, more specifically // to Square::side, which describes the side width of the square. // Ther is an empty declaration of class Square. // This is necessary because within the declaration of Rectangle we refer to // Square (as a parameter in convert()). The definition of Square is included later, // so if we did not include an empty declaration for Square this class would not be // visible from within the definition of Rectangle. // In this example, Rectangle is considered as a friend class by Square, but Rectangle // does not consider Square to be a friend, so Rectangle can access the protected // and private members of Square but not the reverse way. Of course, we could have // declared also Square as friend of Rectangle if we wanted to. // Another property of friendships is that they are not transitive: The friend of a // friend is not considered to be a friend unless explicitly specified. #include using namespace std; class Square; class Rectangle { private: int width, height; public: int area () {return (width * height);} void convert (Square a); }; class Square { private: int side; public: void set_side (int a){ side=a; } friend class Rectangle; }; void Rectangle::convert (Square a) { width = a.side; height = a.side; } int main () { Square sqr; Rectangle rect; sqr.set_side(4); rect.convert(sqr); cout << "The area is " << rect.area(); getchar(); return 0; }