I see in a header that I didn\'t write myself the following:
class MonitorObjectString: public MonitorObject {
// some other declarations
friend inlin
Grammatically speaking...
The friend
keyword is still needed to tell the compiler that this function is not a member of a class, EDIT: but instead a non-member function that can see the private members of the class.
However, this could have been implemented more cleanly like this:
/* friend */ inline bool operator ==(const MonitorObjectString& rhs) const
{ return fVal == rhs.fVal; }
(Of course, I'm assuming fVal
is of a suitable type that can be compared without affecting its const-ness.)
friend inline bool operator==(MonitorObjectString& lhs, MonitorObjectString& rhs) {
return(lhs.fVal==rhs.fVal);
}
is called friend definition
. It will define the function as a non-member function of the namespace surrounding the class it appears in. Actually, the inline there is redundant: It's implicitly declared inline if it's a friend definition. Some pros and cons of it:
MonitorObjectString
. But that's neither good nor bad. It depends on the situation. For example if there are functions getFVal()
making the function friend is pretty pointless. Could use getFVal
as-well then. I used to like this friend definition style of operators, because they have direct access to class members, and appear within the class definition - so I could have "everything with one sight". Recently, however, I came to the conclusion that it's not always a good idea. If you can (and you should) implement the operator purely using public member functions of the class, you should make it a non-friend (and non-member) operator, defined in the same namespace of the class. It makes sure that if you change some implementation - but keep the interface of the class the same - the operator will still work and you have less cascading changes, because you know it can't access implementation details.
However, I prefer this style over writing member operators, because operator functions at namespace scope have the added features of being symmetric with their arguments: They don't treat the left side special, because both sides are just normal arguments and not object arguments that are bound to *this
. If either the left or the right side is of the type of your class, the other side can be implicitly converted - regardless of whether it's left or right. For functions that are also defined without the friend definition syntax (traditionally, at namespace scope), you will have the feature of selectively including headers that make those operators available or not.
They aren't mutually exclusive. "friend" means the non-member function can access the private members of the class. "inline" means there is no function call invocation, the body of the function is duplicated (in assembly) at every call site.