Search code examples
c++friendfriend-function

c++ how to properly declare friend class method of another class


consider the following example.

class A
{
    int member;
};

class B
{
    A& a_ref;
    void manipulate()
    {
        a_ref.member++;
    }
};

Now, obviously, B::manipulate can not access a_ref. I would like to allow (only) class B to get (reference) to A::member. I know that there exists friend keyword, but I do not know how to use it properly. My intention is, that I could change B::manipulate implementation to become this

int& A::only_B_can_call_this() // become friend of B somehow
{
    return member;
}

void B::manipulate()
{
    a_ref.only_B_can_call_this()++;
}

Solution

  • To make B a friend:

    class A
    {
        int member;
        friend /*class*/ B;  // class is optional, required if B isn't declared yet
    };
    

    Note that friends are anti-patterns - if something is private, it probably shouldn't be accessed. What are you trying to accomplish? Why isn't A self-contained? Why does another class need to access its internal data?

    Use friend if you have valid answers/reasons for these questions.