I have a question with friend function in C++. I understand that if a function is defined as a friend function of a class, it can access any member variables or function regardless whether it is private, protected or public. Recently I am using doxygen to create document reference, I find another advantage of friend function: its relation with the class can be easily illustrated as friend function will be listed after the member function in the HTML page. However, if the function is not defined as friend, it will be regarded as a global function, and with doxygen it will not be listed with the class documentation. Then I plan to make all the global functions that have relationship with a specific class as its friend functions. I was wondering whether this is a good practice.
The following codes show one function can be chosen as either as a friend function or a global function.
#include <iostream>
#include <map>
#include <set>
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
#include <numeric>
#include <string>
using namespace std;
class ABCD
{
public:
int a;
int b;
friend void friend_fun(const ABCD &obj);
};
void fun(const ABCD &obj)
{
std::cout<<obj.a<<endl;
std::cout<<obj.b<<endl;
};
void friend_fun(const ABCD &obj)
{
std::cout<<obj.a<<endl;
std::cout<<obj.b<<endl;
};
int main ()
{
ABCD obj;
obj.a = 20;
obj.b = 30;
fun(obj);
friend_fun(obj);
return 0;
}
Doxygen allows you to create and refer to groups of functions and other global things. That would make a lot more sense than breaking useful language-level protection just to exploit a quirk of Doxygen’s behaviour.