Search code examples
c++operator-overloadingfriend

Making a member function a friend


What happens when you make a member function of a class a friend of itself!?

The code below compiles and runs. Without the friend declaration a 'too many arguments to operator' is generated (and rightly so). I realise that doing this doesn't make any sense but can anyone tell me what is happening here? Does friend force the compiler to omit the default this parameter in some way?

class Test
{
public:
  friend bool operator<(Test& lhs, Test& rhs)
  {
     return true;
  }
};

int main( int c, char** argv)
{
  Test test1;
  Test test2;

  return test1 < test2;
}

Solution

  • The difference is that a friend is not a member even if the entire definition appears inside the class; rather, the function is placed in the surrounding namespace. So, there is no this pointer. While a member operator< operates implicitly on this and the explicit right-hand-side argument, a friend needs both left- and right-hand side argument provided explicitly as function parameters - hence the extra parameter. Your friend version is equivalent to putting the function after the class, except that it has access to the private and protected members and bases and is implicitly inline (though that doesn't mean the compiler has to inline it - it's only a hint, but it's important with respect to the One Definition Rule in that your friend function can be included from many translation units and link without issues).