Search code examples
c++friend

public friend function in C++?


I saw some code in C++ and have a question about it:

  class CRectangle {
        int width, height;
      public:
        friend CRectangle duplicate (CRectangle);
    };

The variables width and height are private, and the method duplicate() is public. The keyword friend is for accessing the private and protected functions outside of a CRectangle object, but duplicate() is already public. If it can be accessed from the outside, why do we need "friend"?

Does this mean that, although we directly call a public method like duplicate() outside of the class, if the method accesses some private variable, it is also not allowed and we have to declare it as "friend?"

This is the implementation of the duplicate() function; I just want to make the question clear:

CRectangle duplicate (CRectangle rectparam)
{
  CRectangle rectres;
  rectres.width = rectparam.width*2;
  rectres.height = rectparam.height*2;
  return (rectres);
}

Solution

  • If you remove friend, this function will become a method - a function, that is declared inside the class and is a public method (as there's public: )

    If you put friend in front of duplicate, this means that you declare a function, that is not a member of the class, that takes one argument - CRectangle and that have access to private/protected members of the class.

    The second case requires definition for CRectangle duplicate( CRectangle )

    Both cases are different.


    EDIT: For friend, the access specifier doesn't matter.

    By "The second case requires definition for CRectangle duplicate( CRectangle )", I mean, that the first case requires definition, too, but it is

    //         vvvvvvvvvvvv
    CRectangle CRectangle::duplicate( CRectangle )