Static member

When we add a static data member in class, it will have only one copy per class.
Let us understand with an example.
//Header file
#include <iostream>
using namespace std;
class base {
    static unsigned int m_classMember; //static data member
    unsigned int m_objectMember; //nonstatic data member
public:
    base() {
        m_objectMember = 0;
        ++ m_classMember;
        ++ m_objectMember;
       cout << “Count: “ << m_classMember  << “ “ << m_objectMember <<
          endl;
    }
};

//Source file:
unsigned int base:: m_classMember = 0;  //Initialization of static data member outside the class
int main() {
    base b1;
    base b2;
    cout << “Object size: “ << sizeof(b1) << endl;
    return 0;
}

Output:
Count: 1 1
Count: 2 1
Object size: 4

Observations from the above program:

  • We have two data members in the base class. One is static(class level
    member) and other is nonstatic(object level member).
  • m_classMember variable is incremented by one for each object creation by retaining the previous value. This means that static data member retains its value across objects. In other words, static data member has one copy per class unlike nonstatic data members that keeps separate copy per object.
  • Static data members does not contribute to the size of the object. In the output, object size is 4 bytes which is size of an int. This means static data member is not included in the object size.
  • Static data member can be accessed through static function, constructor and normal member function. In const function also, static data member can be accessed.
  • Static data member must be initialized outside the class as shown in the above example otherwise compiler(specifically linker) will throw an error.
  • Static data member of a class must be initialized only once across all the translation units otherwise linker will report an error.
  • Static data members have external linkage. This means that static data member variable name must be unique across the entire translation units.
  • static data members can be accessed outside without an object using scope resolution operator provided it is declared under public access specifier.

In general, static data member is required when we want the data member to be accessed across the objects.



Related posts