2.9. The Keyword static

[ fromfile: statics.xml id: statics ]

static Local Variables

static Class Members

[Note]Global Namespace Pollution

Adding names to the the global scope (e.g., by declaring global variables or global functions) is called global namespace pollution and is regarded as bad programming style. There are many good reasons to avoid declaring global variables in your programs. One is that it increases the likelihood of name collisions and confusion. Some experts use the number of global names in a program as an inverse measure of the program's quality (the lower the number, the higher the quality).

Example 2.9. src/statics/static.h

[ . . . . ]
class Thing {
public:
    Thing(int a, int b);
    ~Thing();
    void display() const ;
    static void showCount();
private:
    int m_First, m_Second;
    static int s_Count;
};
[ . . . . ]

Figure 2.3.  UML Class Definition with static

UML Class Definition with static

Example 2.10. src/statics/static.cpp

#include "static.h"
#include <iostream>

int Thing::s_Count = 0;        1

Thing::Thing(int a, int b)
        : m_First(a), m_Second(b) {
    ++s_Count;
}

Thing::~Thing() {
    --s_Count;
}

void Thing::display() const {
    using namespace std;
    cout << m_First << "$$" << m_Second;
}

void Thing::showCount() {      2
    using namespace std;
    cout << "Count = " << s_Count << endl;
}

1

Must initialize static member!

2

Static function.


[Note]Note

Notice that the term static does not appear in the definitions of s_Count or showCount(). For the definition of s_Count, the keyword static would mean something quite different: It would change the scope of the variable from global to file-scope (see Section 20.2). For the function definition, it is simply redundant.

Block-scope Static

long nextNumber() {
    int localvar(24);
    static long statNum = 1000;
    cout << statNum + localvar;
    return ++statNum;
}

static Initialization

Example 2.11. src/statics/static-test.cpp

#include "static.h"

int main() {
    Thing::showCount();     1
    Thing t1(3,4), t2(5,6);
    t1.showCount();         2
    {                       3
        Thing t3(7,8), t4(9,10);
        Thing::showCount(); 4 
    }                       5

    Thing::showCount(); 
    return 0;
}

1

At this point, no objects exist, but all class statics have been initialized.

2

Access through object.

3

An inner block of code is entered.

4

Access through class scope resolution operator.

5

End inner block.




[17] The exception to this rule is a static const int, which can be initialized in the class definition.

[18] Chapter 7, "Libraries and Design Patterns"