STATIC DATA MEMBER & MEMBER FUNCTIONS Ritika sharma
STATIC DATA MEMBERS It is normally used to maintain values common to the entire class. For ex: It can be used as counter that records the occurrences of all the objects. Static data member is associated with class not with object. But it is shared by all the objects of a class.(it may exist if no object of a class it created. Initialized to Zero , when first object of class is created. Ritika sharma
class abc { private: static int count; int number; public: void getdata(int a) { cout <<"enter no"<<endl; number=a; count++; } void getcount() cout<<"count:=="; cout<<count; }; int abc :: count ; Ritika sharma
int abc :: count ; int main() { abc a,b; a.getcount(); b.getcount(); a.getdata(100); b.getdata(200); return 0; } Ritika sharma
PURPOSE OF MAKING DATA MEMBER STATIC It is used to maintain Data which is specific for class not for object. Only one copy of that member is created for the entire class and is shared by all the objects of the class. Virtually eliminates need of GLOBAL Variable. Static data member behave exactly like global variable, difference is what its scope is within the class, global variable scope is within the program. Its lifetime is entire program , and is visible only within the class. Ritika sharma
How static data member can be accessed With the class name followed by the scope resolution operator. Definition is done outside the class scope(in addition to the declaration within the class scope to avoid linker error. Ritika sharma
Static Member function Its is also not associated with object. It cannot access non-static data members Can be ACCESSED with the class name followed by resolution operator. It is used to read /write static data members ,as for encapsulation data members should be kept private. Ritika sharma
class abc { private: static int count; int number; public: void getdata(int a) { cout <<"enter no"<<endl; number=a; count++; } static void getcount() cout<<"count:=="; cout<<count; }; int abc :: count ; Ritika sharma
int abc :: count ; int main() { abc a,b; abc::getcount(); a.getcount(); b.getcount(); a.getdata(100); b.getdata(200); return 0; } Ritika sharma