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?
Unlike free-standing static
functions in the implementation file, private static member functions can be used in the header of the class. This is important in situations when you want to inline a non-private member function, which calls your private static function:
class Demo {
private:
static std::string sanitize(const std::string& name);
std::string name;
public:
Demo(const std::string& n) : name(sanitize(n)) {
}
};
Doing the same with free-standing static functions would require implementing Demo
's constructor in the cpp file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With