Friend class
In object-oriented programming to allow access to "private" or "protected" data of a class in another class, the latter class is declared as a friend class.
Purpose
A friend class gives another class full access to its private and protected data and methods.
Example
//A friend class can be declared as:
class A
{
private:
//...(statements)
public:
//...(statements)
friend class B;
}
In this example class B has access to private and protected data and member functions of class A.
Declaration
Friend declarations can go in either the public, private, or protected section of a class--it doesn't matter where they appear. In particular, specifying a friend in the section marked protected doesn't prevent the friend from also accessing private fields.
Scope
Property of friendships is that they are not transitive: The friend of a friend is not considered to be a friend unless explicitly specified.
Example
class A {
friend class B; int a;
};
class B {
friend class C;
};
class C {
void f(A* p) { p->a = 2; }
};
The compiler would not allow the statement p->a = 2 because class C is not a friend of class A, although C is a friend of a friend of A.
Features
References
- An Introduction to Object-Oriented Programming in C++: with Applications in Computer Graphics, by Graham M. Seed
See also
External links
- C++ Language Tutorial
- 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/