Saturday 6 April 2019

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

count:0
count:0
count:0
After reading data
count:3
count:3
count:3

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

class-name::function-name;

For example

using namespace std;

class Demo
{
 private: 
  static int X;

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

//defining
int Demo :: X =10;


int main()
{
 Demo X;

 X.fun();
 
 return 0;
}

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top