views:

170

answers:

4

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?

+3  A: 

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.

anon
I didn't quite understand your example of public members, but otherwise I agree with your answer.
Helltone
@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
+2  A: 

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.

Etienne de Martel
+6  A: 

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.

Praetorian
That causes a rather complex change in semantics. It would be rather hard to explain in a comment here, but basically name lookup differs.
MSalters
@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
A: 

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.

orangeoctopus
The 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