Static Member Variables

Introduction

Static member variables only exist once in a program regardless of how many class objects are defined.

Example: The below program shows that the value we set using cFirst can be accessed using cSecond!

class Something
{
public:
    static int s_nValue;
};
 
int Something::s_nValue = 1;
 
int main()
{
    Something cFirst;
    cFirst.s_nValue = 2;
 
    Something cSecond;
    std::cout << cSecond.s_nValue;
 
    return 0;
}

Static members belong to the class itself, not the objects of the class. So the above example is better to be written as:

class Something
{
public:
    static int s_nValue;
};
 
int Something::s_nValue = 1;
 
int main()
{
    Something::s_nValue = 2;
    std::cout << Something::s_nValue;
    return 0;
}

Initializing static member variables

  • You must explicitly initialize the static member. int Something::s_nValue = 1
  • This code shoulb be placed in the code file for the class (eg. Something.cpp)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.