C++ Programming (using friend class)

A class may name another function or another class as its friend. That gives the named function the right to access all private features (strangely, friends are so powerful!). This is a dangerous mechanism and shouldn’t be used unless necessary!

Characteristic of Friendship:
• Friendship is not mutual unless explicitly specified as such.
• Friendship is not inherited.
• Friendship is not transitive. Therefore, if class A is a friend of class B, and class B is a friend of class C, we cannot infer that class C is a friend of class A.

Common Usage:
• to allow nested classes to access the private members of the surrounding class;
• to access the private members of other nested classes;
• to allow the surrounding class to access the private members of nested classes.

Example: In linked list, the list and node objects
Syntax:

class A {
private:
……..
friend class B;
};

Note that class B above can access the private members of class A because class A declare it as a friend.
Examples:

class Surround
{
public:
class FirstWithin
{
friend class Surround; //Allows Surround to access private members
public:
int getValue();
private:
static int variable;
};
int getValue()
{ // inline member function of Surround
FirstWithin::variable = SecondWithin::variable;
return (variable);
}

private:
class SecondWithin {
friend class Surround;
public:
int getValue();
private:
static int variable;
};
static int variable;
};