6

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?

Giovanni Funchal
  • 8,934
  • 13
  • 61
  • 110

4 Answers4

6

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
  • 106,671
  • 19
  • 240
  • 328
  • 1
    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 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
3

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.

  • 1
    I 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
2

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
  • 34,692
  • 8
  • 91
  • 111
0

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.

Donald Miner
  • 38,889
  • 8
  • 95
  • 118
  • 2
    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 Jul 13 '10 at 23:41