0

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()++;
}
Zereges
  • 5,139
  • 1
  • 25
  • 49

2 Answers2

2

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

You simply add friend class <class_name>; to the class that wants to make its members accessible, where <class_name> is the name of the class that you want to provide access for.

class A
{
    friend class B; // allow class B to access private members of A
    int member;
};

class B
{
    A& a_ref;
    void manipulate()
    {
        a_ref.member++;
    }
};
bku_drytt
  • 3,169
  • 17
  • 19
  • And could I make just one function available to `B`? Also, does accessibility specifier of friendness matter? So, does it matter if `friend` is declared in `public:`/`private:`/`protected:` section? – Zereges Sep 14 '15 at 09:22