Static data members in C++

05 min read

Static Data Members: The characteristics of static member variables are

  • It is initialized to zero when the first object of its class is created. No other initialization is permitted.
  • Only one copy of 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.

Syntax

class className
{
static DataType DataMember;
. . . .
};
DataType className :: DataMember[=InitialValue];

 

Example: Program to count how many calls are made to a member function set()

#include <iostream.h>
class MyClass
{
static int count;         //static data member
int number;
public:
void set(int num)     //initializes object's member and increments function call
{
number=num;
count++;
}

void show( )
{
cout <<"\n Number of calls made
}
};

int MyClass :: count:=0;          //definition and initialization of a data member
int main( )
{
MyClass obj1;
obj 1 .show( );         //Output: Number of cal Is made to set() through any object: 0
obj1.set(100);
obj 1 .show( );       //Output: Number of  made to set() through any object: 1
MyClass obj2,obj3;
obj2.set(200);
obj2.show( );     //Output: Number of calls made to set() through any object: 2
obj2.set(250);
obj3.set(300);
obj3.show( );    //Output: Number of calls made to set() through any object: 3
system("pause")•
return 0;
}







 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error