Friend class

suggest change

An entire class may be declared a friend. Every member of the friend class can then access the private and protected members of the class granting friendship:

class Accessor {
public:
    void access_private1();
    void access_private2();
};

class PrivateHolder {
public:
    PrivateHolder(int val) : private_value(val) {}
    friend class Accessor;
private:
    int private_value;
};

void Accessor::access_private1() {
    PrivateHolder ph(10);
    // OK.
    std::cout << ph.private_value << '\n';
}

void Accessor::access_private2() {
    PrivateHolder ph(10);
    // OK.
    std::cout << ph.private_value + 1 << '\n';
}

Friendship is not reciprocal. If two classes need private access in both directions, each must declare the other as a friend.

class Accessor {
public:
    void access_private1();
    void access_private2();
private:
    int private_value = 0;
};

class PrivateHolder {
public:
    PrivateHolder(int val) : private_value(val) {}
    // Accessor is a friend of PrivateHolder.
    friend class Accessor;
    void reverse_access() {
        // Error: friendship is not reciprocal.
        Accessor a;
        std::cout << a.private_value;
    }
private:
    int private_value;
};

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents