C++ static member variables and their initialization

C++ProgrammingServer Side Programming

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;
}
raja
Published on 22-Nov-2018 07:45:05
Advertisements