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;
}
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
thispointer. While a memberoperator<operates implicitly onthisand the explicit right-hand-side argument, afriendneeds both left- and right-hand side argument provided explicitly as function parameters – hence the extra parameter. Yourfriendversion is equivalent to putting the function after the class, except that it has access to theprivateandprotectedmembers and bases and is implicitlyinline(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 yourfriendfunction can be included from many translation units and link without issues).