Friend class

From Wikipedia, the free encyclopedia
Jump to: navigation, search

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[edit]

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[edit]

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
    }
};

class C {
public: 
    C(B b) {
        b.i = 0; // illegal access
    }
};

Properties[edit]

  • Friendships are not symmetric – if class A is a friend of class B, class B is not automatically a friend of class A.
  • Friendships are not transitive – if class A is a friend of class B, and class B is a friend of class C, class A is not automatically a friend of class C.
  • Friendships are not inherited – if class Base is a friend of class X, subclass Derived is not automatically a friend of class X; and if class X is a friend of class Base, class X is not automatically a friend of subclass Derived.

See also[edit]

References[edit]

External links[edit]