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
The friend classes are declared with friend keyword.The freind class can be declared in the public or private or the public menbers of the base class .It doesn't mean that if friend class is declared in the public members of the base class then it doesn't have access to public and private memebers.
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/