Static data members:

  • Data members of the class which are shared by all objects are known as static data members.
  • Only one copy of a static variable is maintained by the class and it is common for all objects.
  • Static members are declared inside the class and defined outside the class.
  • It is initialized to zero when the first object of its class is created. No other initialization is permitted.
  • It is visible only within the class but its lifetime is the entire program.
  • Static members are generally used to maintain values common to the entire class.

Static member functions:

  • Static member functions are associated with a class, not with any object.
  • They can be invoked using class name, not object.
  • They can access only static members of the class.
  • They cannot be virtual.
  • They cannot be declared as constant or volatile.
  • A static member function can be called, even when a class is not instantiated.
  • There cannot be static and non-static version of the same function.
  • A static member function does not have this pointer.

Example:

#include<iostream>

using namespace std;

class item

{

int number;

static int count;

// static variable declaration

public:

void getdata(int a)

{

number = a;

count++;

}

static void getcount()

{

cout<<”value of count: “<<count;

}

};

int item :: count; //

static variable definition

int main()

{

item a,b,c;

a.getdata(100);

b.getdata(200);

c.getdata(300);

a.getcount();

b.getcount();

c.getcount();

getch();

return 0;

}

Output:

value of count:3

value of count:3

value of count:3