0

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?

  • 1
    A static class member is a property of the class. A non-static class member is a property of an object. – Kerrek SB Aug 12 '14 at 18:38
  • 8
    A static member function does not have an instance to work on, unless you pass it one. So it cannot access any non-static members. A non-static member function can. `static` and `const` are unrelated concepts in this context and others. – juanchopanza Aug 12 '14 at 18:39
  • 2
    I recommend against returning a `const` thing. – chris Aug 12 '14 at 18:39
  • static does not have anything to do with const. it is a different modifier. – Richard Chambers Aug 12 '14 at 18:39
  • @chris, sometimes const return is necessary to support the expected meaning of a method such as some operators. – Richard Chambers Aug 12 '14 at 18:41
  • 3
    @RichardChambers, Yes, and it used to be good, but not as of C++11. It inhibits optimizations. – chris Aug 12 '14 at 18:42
  • http://stackoverflow.com/questions/12051012/should-i-return-const-objects – Richard Chambers Aug 12 '14 at 18:53
  • static and const, they are two completely different concepts –  Aug 12 '14 at 18:57
  • @RichardChambers: I see your link, but don't understand how it's related. That link says nothing about returning a `const` value being a good idea. First and third answers don't give opinions, The second, fourth, and fifth answers specifically says that returning by `const` inhibits optimizations and should not be done. – Mooing Duck Aug 12 '14 at 19:04
  • @juanchopanza: A static member function can also create an instance itself, it does not have to be passed one. Besides, although it is clear to me what you mean, I feel the OP may be confused if you say that it "cannot access any non-static members". After all, it can: `struct S { int i; static void f() { S s; s.i = 1; } };`. – Christian Hackl Aug 12 '14 at 19:31

3 Answers3

2

The difference is quite simple:

A static class member works on the class and not on a instance/object of a class. In fact you can not access any data member from a static method. You only can access static members ( methods and attributes ). This is also true for calling other member functions from a static one. It will simply not work, because a static member has no idea of a class instance and is not able to call any non static method!

Under the hood a non static member function get always a hidden pointer the the instance which is simply the this pointer from the view of the class itself. A static member do not need this kind of pointer and can not use it.

If you call a static method, you do not need to create an instance. In fact the class is only a kind of namespace. If you call a static member from an instance variable or pointer to it, the result is the same as you have no instance!

Attention must be paid to static variables. The must be defined outside the class somewhere in an object file! Normally all 'normal' members of a class will be created while creating an instance of the class. A static variable have no instance and so it must be exist somewhere else. This requires a manual definition somewhere as you can see in the example. If you have a class in a header file you can not define the variable there. Only the declaration is inside the class. The definition must be placed in an cpp-file. If you try to define your variable in the header, you can as many instances as includes for this header files which results in multiple definition errors while linking!

Because you ask especially for protection the access to members of the class: A static method can access static variables of the class and also can write them. But you can not use const qualification for static methods!

class A
{   
    public:
        static void Do() { cout << "stat var " << stat_var << endl; }
        void Do2() const { cout << "var" << var << endl; }

        A():var(100) {}

    private:
        static int stat_var;
        int var;


};  

int A::stat_var=9;

int main()
{   
    A a;        // instance of A a
    a.Do2();    // call a method with the instance a

    A::Do();    // call the static method without any instance
    a.Do();    // this looks like a call with a class instance, but it is not!!!
}   
Klaus
  • 24,205
  • 7
  • 58
  • 113
0

static members and const members are separate concepts, used for separate purposes.

Consider the following class:

class fred
{
    int a;

    public:
    fred( int aa ) : a(aa) { }

    int what( int b ) const 
    { 
        return a + b; 
    }

    static int whatnot( fred & f ) 
    {
        f.a = 0;
    }

};

As you can see, the static member whatnot() can manipulate the private members of any instance of the class which is passed to it. It is, after all, a member of the class. It does nothing to guarantee that any particular class instance will not be changed. A const member on the other hand guarantees that the instance it operates on will not be changed.

For helper functions though which have no need for direct access to an object's internals, prefer nonmember nonfriend functions (Item 44 in http://www.gotw.ca/publications/c++cs.htm)

Rob K
  • 8,757
  • 2
  • 32
  • 36
-1

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.

Dko
  • 820
  • 6
  • 12
  • Reducing the number of registers needed to pass parameters should not in anyway be a concern. That reeks of premature optimization. – Rob K Aug 12 '14 at 19:37
  • So why and when would you prefer a static member over a non-member? – juanchopanza Aug 12 '14 at 19:43
  • I'd prefer a static member over a non-member method when you want to use the properties of a class to limit the scope of the method. – Dko Aug 12 '14 at 20:27