C++ static member variables and their initialization


Static C++ member variables are defined using the static keyword. The static member variables in a class are shared by all the class objects as there is only one copy of them in the memory, regardless of the number of objects of the class.

The static class member variables are initialized to zero when the first object of the class is created if they are not initialized in any other way.

A program that demonstrates static member variables and their initialization in C++ is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class Demo {
   public :
   static int num;
   int display() {
      cout << "The value of the static member variable num is: " << num;
   }
};
int Demo::num = 100;
int main() {
   Demo obj;
   obj.display();
   return 0;
}

Output

The output of the above program is as follows.

The value of the static member variable num is: 100

Now let us understand the above program.

In the class Demo, the static class member variable is num. The function display() prints the value of num. The code snippet that shows this is as follows.

class Demo {
   public :
   static int num;
   int display() {
      cout << "The value of the static member variable num is: " << num;
   }
};
int Demo::num = 100;

In the function main(), an object obj of class Demo is created. Then the function display() is called that displays the value of num. The code snippet that shows this is as follows.

int main() {
   Demo obj;
   obj.display();
   return 0;
}

Updated on: 26-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements