The data members and functions of a class is not accessible if their are being defined as private or protected. If you try to access its function right after you initialized the class object, the compiler will complaint about the error and that it cannot access the private or protected function. In some circumstances, you may want to access the private or protected member function in order to accomplish certain process in your project. So, how could you access to these private or protected member function? Well, the answer is simple, you can declare a friend function to access all the private or protected member function in a class. The following example will demonstrate how you can call the Compute() function which is defined as private function in the Test class. Let’s create a Test class with a Compute() private function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using namespace std;

class Test
{
  // This is the declaration of friend function
  friend int GetCompute(Test *);

public:
  Test(int x, int y)
  {
    a = x;
    b = y;
  }

private:
  // this is a private funtion
  int Compute()
  {
    return a + b;
  }

private:
  int a;
  int b;
};
We need to implement the friend function now.
1
2
3
4
5
int GetCompute(Test *t)
{
  // access to private function in Test class
  return t->Compute();
}
Finally, initialize and call the friend function in main function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int _tmain(int argc, _TCHAR* argv[])
{
  // Initialize the Test class
  Test * t = new Test(1, 2);

  // If you enable the following line, the compiler will complaint
  //int sum = t->Compute();
 
  // Access the private Compute() thru friend function
  int sum = GetCompute(t);

  // Display the result
  printf("Sum = %d\n", sum);

  return 0;
}
Download sample source code: C++ Friend Function Example