ereOn
ereOn

Reputation: 55736

Friend class definition

Today I looked into the header source code of boost::asio::ip::address and found the following lines:

class address
{
  // I removed some irrelevant lines here...

  public:

  /// Compare addresses for ordering.
  friend bool operator>=(const address& a1, const address& a2)
  {
    return !(a1 < a2);
  }
};

Now I know what friend is for but I had never seen it followed by a definition, inside a class definition.

So my question is, what does this friend declaration do ? It seems to me that operator>= is not a method here, however there is no static keyword either.

Does friend replace static in this particular case ?

Upvotes: 4

Views: 156

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

Yes and no. It doesn't replace static because you don't need to qualify the name when you call the operator. It kind of does as you don't need a class instance to call it on.

It's like declaring the operator outside the class:

class address
{
  // I removed some irrelevant lines here...

  public:

  /// Compare addresses for ordering.
  friend bool operator>=(const address& a1, const address& a2);
};

inline bool operator>=(const address& a1, const address& a2)
{
   return !(a1 < a2);
}

You can access private and protected methods from the class.

Think of overloading the stream operator inside the class, the same technique can be applied.

Upvotes: 2

Related Questions