Static Data members in C++

When we declare a normal variable (data member) in a class, different copies of those data members create with the associated objects.

In some cases when we need a common data member that should be same for all objects, we cannot do this using normal data members. To fulfill such cases, we need static data members.

Static Variables in C++

Static Data members are created using "static" keyword in C++. The properties of static member variables are similar to that of a C static variable. A static member variable has certain special characteristics. These are:
  1. It is initialized to zero when the first object of its class is created. No other initialization is permitted.
  2. Only one copy if the that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
  3. It is visible only within the class, but its lifetime is the entire program.
For example consider  the following program

The out put of the above program is

After reading data

In the above program, the following line was written, to define static data members.

int item::count;

This is necessary because the static data members are stored separately rather than as a part of an object.

Static Methods in C++

Like static member variables, we can also have static member functions. A member function that is declared static has the following properties:
  1. A static function can have access to only other static members (functions or variables) declared in the same class.
  2. A static member function can be called using the class name as follows


For example

using namespace std;

class Demo
  static int X;

  static void fun()
   cout <<"Value of X: " << X << endl;

int Demo :: X =10;

int main()
 Demo X;;
 return 0;

1 comment:

  1. Inside the structure of this article, we use it to allude to our labyrinth inside the class of a similar name. ExcelR Data Science Courses