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.
Another common version of Andrew's example, the dreaded code-couplet
parent.addChild(child);
child.setParent(parent);
Instead of worrying if both lines are always done together and in consistent order you could make the methods private and have a friend function to enforce consistency:
class Parent;
class Object {
private:
void setParent(Parent&);
friend void addChild(Parent& parent, Object& child);
};
class Parent : public Object {
private:
void addChild(Object& child);
friend void addChild(Parent& parent, Object& child);
};
void addChild(Parent& parent, Object& child) {
if( &parent == &child ){
wetPants();
}
parent.addChild(child);
child.setParent(parent);
}
In other words you can keep the public interfaces smaller and enforce invariants that cut across classes and objects in friend functions.