Jump to content

Friend class

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Nalawadec (talk | contribs) at 16:49, 11 September 2011. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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.

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.

References

  • An Introduction to Object-Oriented Programming in C++: with Applications in Computer Graphics, by Graham M. Seed

See also