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 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
Ais a friend of classB, classBis not automatically a friend of classA. - Friendships are not transitive – If class
Ais a friend of classB, and classBis a friend of classC, classAis not automatically a friend of classC. - Friendships are not inherited – A friend of class
Baseis not automatically a friend of classDerivedand vice versa; equally ifBaseis a friend of another class,Derivedis not automatically a friend and vice versa. - Access due to friendship is inherited – A friend of
Derivedcan access the restricted members ofDerivedthat were inherited fromBase. Note though that a friend ofDerivedonly has access to members inherited fromBaseto which Derived has access itself, e.g. ifDerivedinherits publicly fromBase,Derivedonly has access to the protected (and public) members inherited fromBase, not the private members, so neither does a friend.
See also
References
External links
- http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr043.htm
- http://www.cplusplus.com/doc/tutorial/inheritance/
This article is issued from Wikipedia - version of the Tuesday, November 24, 2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.