Search code examples
c++function-declaration

C++ - declaring a function 'static' versus the form 'const int function_name() const'


My eyes were recently opened to the uses of the static keyword in regards class 'helper functions'. It is my understanding now that you declare a member function static IF it does not interact with any data members but instead works only on the parameters passed to it - a kind of 'insurance' that it will not inadvertently alter the class itself.

Previously I was vaguely aware of this kind of situation and did much the same kind of pro-active 'protection' by declaring a function in the form:

 const int function_name(int parameter_one, int parameter_two) const;

My understanding was the const after the function name prevents any class data members being altered inside that function.

I do not really see the difference nor why 'static' is a better was of achieving this kind of 'protection'. Clearly I am missing some nuances here, despite grasping the basics. Could someone explain to me the subtleties in these uses of code?


Solution

  • The big advantage for static methods is that you do not need a pointer to the class to be able to call the method. I've reviewed some complex code that passed pointers as parameters many times so that methods (that could be static) could be called. Using static methods can simplify code and perhaps reduce the number of registers needed to pass parameters, if it works for the situation. Since you can use only one or the other, you should choose which works best for you.