Friends (C++ only)

A friend of a class X is a function or class that is not a member of X, but is granted the same access to X as the members of X. Functions declared with the friend specifier in a class member list are called friend functions of that class. Classes declared with the friend specifier in the member list of another class are called friend classes of that class.

A class Y must be defined before any member of Y can be declared a friend of another class.

In the following example, the friend function print is a member of class Y and accesses the private data members a and b of class X.

#include <iostream>
using namespace std;

class X;

class Y {
public:
  void print(X& x);
};

class X {
  int a, b;
  friend void Y::print(X& x);
public:
  X() : a(1), b(2) { }
};

void Y::print(X& x) {
  cout << "a is " << x.a << endl;
  cout << "b is " << x.b << endl;
}

int main() {
  X xobj;
  Y yobj;
  yobj.print(xobj);
}

The following is the output of the above example:

a is 1
b is 2

You can declare an entire class as a friend. Suppose class F is a friend of class A. This means that every member function and static data member definition of class F has access to class A.

In the following example, the friend class F has a member function print that accesses the private data members a and b of class X and performs the same task as the friend function print in the above example. Any other members declared in class F also have access to all members of class X.

#include <iostream>
using namespace std;

class X {
  int a, b;
  friend class F;
public:
  X() : a(1), b(2) { }
};

class F {
public:
  void print(X& x) {
    cout << "a is " << x.a << endl;
    cout << "b is " << x.b << endl;
  }
};

int main() {
  X xobj;
  F fobj;
  fobj.print(xobj);
}

The following is the output of the above example:

a is 1
b is 2

You must use an elaborated type specifier when you declare a class as a friend. The following example demonstrates this:

class F;
class G;
class X {
  friend class F;
  friend G;
};

The compiler will warn you that the friend declaration of G must be an elaborated class name.

You cannot define a class in a friend declaration. For example, the compiler will not allow the following:

class F;
class X {
  friend class F { };
};

However, you can define a function in a friend declaration. The class must be a non-local class, function, the function name must be unqualified, and the function has namespace scope. The following example demonstrates this:

class A {
  void g();
};

void z() {
  class B {
//    friend void f() { };
  };
}

class C {
//  friend void A::g() { }
  friend void h() { }
};

The compiler would not allow the function definition of f() or g(). The compiler will allow the definition of h().

You cannot declare a friend with a storage class specifier.

Related information



[ Top of Page | Previous Page | Next Page | Contents | Index ]