Friend class

A friend class in C++ can access the private and protected members of the class in which it is declared as a friend.[1]

Rationale

Friendship may allow a class to be better encapsulated by granting per-class access to parts of its API that would otherwise have to be public.[2] This increased encapsulation comes at the cost of tighter coupling due to interdependency between the classes.[3]

Example

class B {
    friend class A; // A is a friend of B

private:
    int i;
};

class A {
public: 
    A(B b) {
        b.i = 0; // legal access due to friendship
    }
};

Properties

See also

References

External links


This article is issued from Wikipedia - version of the 11/6/2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.