When are static C++ class members initialized?

C++ProgrammingServer Side Programming

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

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

A program that demonstrates static class members in C++ is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class Example {
   public :
   static int a;
   int func() {
      cout << "The value of static member a: " << a;
   }
};
int Example::a = 20;
int main() {
   Example obj;
   obj.func();
   return 0;
}

Output

The output of the above program is as follows.

The value of static member a: 20

Now let us understand the above program.

In the class Example, the static class member is a. The function func() displays the value of a. The code snippet that shows this is as follows.

class Example {
   public :
   static int a;
   int func() {
      cout << "The value of static member a: " << a;
   }
};
int Example::a = 20;

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

int main() {
   Example obj;
   obj.func();
   return 0;
}
raja
Published on 21-Nov-2018 12:46:51
Advertisements