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 13:03, 18 September 2011 (Declaration). 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.

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

}