Jump to content

Friend class

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 89.133.4.243 (talk) at 19:32, 24 November 2015 (Example). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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 between classes.[3]

Example

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

private:
    int i;


};

class A {
public: 
    A(B b) {//Note that the object has to be passed as a parameter to the function
        b.i = 0; // legal access due to friendship
    }
};

Features

  • 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 – A friend of class Base is not automatically a friend of class Derived and vice versa; equally if Base is a friend of another class, Derived is not automatically a friend and vice versa.
  • Access due to friendship is inherited – A friend of Derived can access the restricted members of Derived that were inherited from Base. Note though that a friend of Derived only has access to members inherited from Base to which Derived has access itself, e.g. if Derived inherits publicly from Base, Derived only has access to the protected (and public) members inherited from Base, not the private members, so neither does a friend.

See also

References