Skip to content

Commit

Permalink
Modify rule S2807: Add a longer explanation of the hidden friend pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
frederic-tingaud-sonarsource authored Jun 27, 2024
1 parent 629afcc commit 81b87b7
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion rules/S2807/cfamily/rule.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,23 @@ This rule raises issues for overloaded binary mathematical and relational operat
== Why is this an issue?

When overloading binary or relational operators, it is recommended that they be declared hidden friends of the class.
A hidden friend, i.e. a friend function defined in the class body, provides the following benefits:

=== The hidden friend pattern

The hidden friend pattern consists of declaring and defining a function directly as a friend inside the class body. This reduces the function's visibility to argument-dependent lookup only. Approximately, such a function is considered only when called on an object of the enclosing class.

[source,cpp]
----
struct MyClass {
friend void function(MyClass const& arg) { // This function is a hidden friend of MyClass
...
}
};
----

=== Benefits of hidden friends

Using hidden friends provides the following benefits:

* in contrast to the member function, it allows conversion to be applied to both operands
* in contrast to free functions, it is considered only if one of the operands is an object of the given class
Expand Down

0 comments on commit 81b87b7

Please sign in to comment.