23

Is there any advantage to using private (probably also static) functions in a class for utility functions used in my class that do not need access to an instance's data over using global static functions in my .cpp file that implements the class?
The first sounds cleaner to me, but the second really makes more sense as these functions do not need to even be mentioned in the .h file.

Baruch
  • 20,590
  • 28
  • 126
  • 201

4 Answers4

13

I would not put private static functions to the header file if they are not needed. They would just pollute the header file and add more work.

But private static functions may be needed when you have a template method/function in a class and want to use that helper function in it.

Another reason for using private static functions instead of global static functions is that they can access private class members (variables, functions).

Juraj Blaho
  • 13,301
  • 7
  • 50
  • 96
5

If a given function relates to your class then you are right. You should make them private static within your class body.

[Note: If those utility function doesn't relate at all then you can think about enclosing them in a namespace or another Util class and keep it within the file scope.]

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • 2
    it can relate to class implementation, not class interface, as in most cases. in this case no need to pollute class interface – Andriy Tylychko Jul 27 '11 at 10:09
4

Just make them file-static functions. If they don't have anything to do with the class, don't put them there.

zvrba
  • 24,186
  • 3
  • 55
  • 65
  • 2
    I would recommend unnamed namespace function instead of file-static one – Andriy Tylychko Jul 27 '11 at 10:08
  • 1
    I am aware that "modern c++" recommends using functions in unnamed namespaces instead, but I fail to see any technical advantage. In fact, it might be disadvantageous since such function has external linkage and may slow down linking. – zvrba Jul 27 '11 at 10:56
  • http://stackoverflow.com/questions/154469/unnamed-anonymous-namespaces-vs-static-functions – Andriy Tylychko Jul 27 '11 at 11:49
  • yeah, it's quite subtle. The most important [is the answer about ODR](http://stackoverflow.com/questions/154469/unnamed-anonymous-namespaces-vs-static-functions/155556#155556), if you wish to discuss it - comment this answer. Also the fact that static functions are deprecated by standard should convince you - standard defines the rules – Andriy Tylychko Jul 27 '11 at 12:36
  • ODR applies to types, not functions. Since static function has internal linkage, it is impossible to violate ODR. (If you violate ODR by providing two definitions for a function, the linker will eventually complain.) – zvrba Jul 27 '11 at 12:57
0

If the private function doesn't modify the class members, it doesn't have any advantage over the global static. Being inside or outside the class makes no difference

mihai
  • 37,072
  • 9
  • 60
  • 86