Is there a way to detect (for instance with compiler warning) if classes are declared friend
but do not access private members, ie. when friendship is useless?

- 8,934
- 13
- 61
- 110
-
1Maybe you can stick together a program using the Clang libraries? – Johannes Schaub - litb Jul 13 '10 at 13:38
4 Answers
I don't know how to detect this using compiler warnings but another way of doing this would be to go to your class definition file and do a search & replace for friend class
with /*friend*/ class
and see if it still compiles. Of course, this could get rather tedious for a large project.

- 106,671
- 19
- 240
- 328
-
1That causes a rather complex change in semantics. It would be rather hard to explain in a comment here, but basically name lookup differs. – MSalters Jul 13 '10 at 14:22
-
1@MSalters: Do you have a link where I can go read about it at? I'm curious to know what the change in semantics is. – Praetorian Jul 13 '10 at 17:07
Compiler warnings are not standardised, so this depends on your specific compiler(s). I would be very surprised if any of them supported this, however. A similar situation would be if you had a public member function which was only called by other public members (meaning it needn't be public), and once again I don't think any compilers detect this.
Doing either of these tests would mean extra work for the compiler writers, and I doubt if they would see them as sufficiently useful to implement.
-
1I didn't quite understand your example of public members, but otherwise I agree with your answer. – Giovanni Funchal Jul 13 '10 at 13:55
-
@Helltone: I guess he means that if a public member function is accessed only through other functions of the same class, it need not be public at all. – casablanca Jul 13 '10 at 15:38
Not that I know of. Maybe there's a refactoring tool out there that can do it. You can always try removing the friendship and see if it still compiles, but that might be time consuming for a large project.

- 34,692
- 8
- 91
- 111
You could compile the code to see that it compiles, then remove all 'friend' declarations (perhaps programmatically with sed) and sees if it still compiles.

- 38,889
- 8
- 95
- 118
-
2The following macro is an easy way to turn 'friend' (and the rest of that line of code) into a comment. This won't work if the friend declaration is multi-line. #define friend // – Aaron McDaid Jul 13 '10 at 23:41