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 is accessed only through static function. Constructor and const function is an exception to this rule( We can see that m_classMember is incremented in the constructor). Similarly, it can be modified through const function as well.
  • Static data member must be initialized outside the class as shown in the above example.
  • Static data members have external linkage. This means that static data member variable name must be unique across the entire translation units.

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



Related posts