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:04, 18 September 2011 (Features). 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

An important feature of friend class is inheritance .Inheritance allows the friend class to access the members of the base class the one in which the friend class has been declared. But it is important to note that if class b is declared as friend class base class a then only then only b can access the members of a and not viceversa.The base class a can access the members of only if it is declared as friend of a class b.It is important to note that the friendship is not transitive which means that suppose class b is friend of base class a and c is friend of b then it doesn't mean that c is a friend of a unless explicitly specified. So from this you can see inheritance between friendclass is different from that of the inheritance between classes.There are no restriction on the accessibility of memebers of the base class for the class which is a freind of the base class.

References

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

See also

}