Search code examples
c++functionmethodsstaticprivate

Is there a Necessity for private static Methods?


The Principle Engineer at my last company had a rule that private static methods should be implemented as functions in the implementation file, not as class methods.

I don't remember if there were any exceptions to his rule. I have stumbled into the motivation for it at my current job: If the arguments or return type of the function in question are objects that would require the inclusion of a definition file in the header, this can cause unnecessary difficulties.

That's enough to steer me away from ever using a private static method again, but before I wrote them off I wanted to know if anyone is aware of a niche they fill that an implementation file function would not?

EDIT:

An example may be helpful here. Say this is the start of the declaration of class Foo, which has other methods which will call void foo() in the implementation file:

class Foo {
    static void foo();

So foo is only accessible by other methods of Foo. Why wouldn't I just define foo in the implementation file, and keep it out of the header all together?


Solution

  • Member functions have access to all private members of the class. If a function needs access to these members, it should be a member. This applies whether or not it's static.

    A static function is one that doesn't operate on a specific object. However, it can still receive objects as parameters. For example:

    class A
    {
        int m;
    
        static int process_3_objects_in_some_way(A x, A y, A z)
        {
            return x.m + y.m + z.m;
        }
    }
    

    Another reason to make a function static is the order of parameters. For example, print:

    class A
    {
        int m;
    
        static void print(std::ostream& stream, A x, int options)
        {
            stream << "Value is: " << (x.m * 1000000 + options);
        }
    }