Search code examples
c++class-designfriend

Is C++ friendship among peers healthy?


Although class friendship is one of the last resorts of C++, does this pattern make sense?

class Peer
{
public:
    friend class Peer;
    void GetSecret(const Peer& other)
    {
        const std::string& secret = other.GiveSecret();
        std::cout << secret << std::endl;
    }

private:
    const std::string& GiveSecret() const
    {
        return "secrety stuff";
    }
};

int main(int argc, char* argv[])
{
    Peer peerA;
    Peer peerB;
    peerA.GetSecret(peerB);
    return 0;
}

Ok the reason for this pattern is because the Peers are all of the same rank, and they need to share knowledge among each other, however this knowledge is secret, because no one but the peers should use it, or the program is no longer valid.

One very real example of this is that when one peer is copy-constructed from another peer it needs to access secret information from its source peer, but again there is no reason for anyone else to know about these internals, just the peers.


Solution

  • friend is not necessary in this case. An object of a class can access the private members of any other object of the same type. It should work just fine without the friend declaration.