I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.
Friends are also useful for callbacks. You could implement callbacks as static methods
class MyFoo
{
private:
static void callback(void * data, void * clientData);
void localCallback();
...
};
where callback
calls localCallback
internally, and the clientData
has your instance in it. In my opinion,
or...
class MyFoo
{
friend void callback(void * data, void * callData);
void localCallback();
}
What this allows is for the friend to be a defined purely in the cpp as a c-style function, and not clutter up the class.
Similarly, a pattern I've seen very often is to put all the really private members of a class into another class, which is declared in the header, defined in the cpp, and friended. This allows the coder to hide a lot of the complexity and internal working of the class from the user of the header.
In the header:
class MyFooPrivate;
class MyFoo
{
friend class MyFooPrivate;
public:
MyFoo();
// Public stuff
private:
MyFooPrivate _private;
// Other private members as needed
};
In the cpp,
class MyFooPrivate
{
public:
MyFoo *owner;
// Your complexity here
};
MyFoo::MyFoo()
{
this->_private->owner = this;
}
It becomes easier to hide things that the downstream needn't see this way.