// Friends are functions or classes declared with the friend keyword. // If we want to declare an external function as friend of a class, // thus allowing this function to have access to the private and // protected members of this class, we do it by declaring a prototype // of this external function within the class, and preceding it with // the keyword friend. #include using namespace std; class Rectangle { private: int width, height; public: void set_values (int, int); int area () {return (width * height);} friend Rectangle duplicate (Rectangle); }; void Rectangle::set_values (int a, int b) { width = a; height = b; } // NOTE: this function is NOT in the class Rectangle Rectangle duplicate (Rectangle rectparam) { Rectangle rectres; rectres.width = rectparam.width*2; rectres.height = rectparam.height*2; return (rectres); } // The duplicate function is a friend of Rectangle. From within that // function we have been able to access the members width and height // of different objects of type Rectangle, which are private members. // Notice that neither in the declaration of duplicate() nor in its // later use in main() have we considered duplicate a member of class // Rectangle. It isn't! It simply has access to its private and // protected members without being a member. int main () { Rectangle rect, rectb; rect.set_values (2,3); rectb = duplicate (rect); cout << "Area is " << rectb.area(); getchar(); return 0; }