static data member and static member function of class in c++

Static Data Member(स्टेटिक डाटा मेम्बर ):-

Programmer can define static data members in a class using static keyword. there is only one copy of the static member is shared between all the objects of class. All the static data members are initialized with zero according to their static storage class. We can also initialize them outside the class by using class name and the scope resolution operator :: .
प्रोग्रामर static कीवर्ड का प्रयोग कर,क्लास में स्टेटिक डाटा मेम्बर को परिभाषित कर सकता है। स्टेटिक मेम्बर की केवल एक कॉपी ही सभी क्लास ऑब्जेक्ट्स के द्वारा शेयर की जाती है। स्टेटिक डाटा मेम्बर्स को उनकी स्टेटिक स्टोरेज क्लास के अनुसार प्रारंभिक मान शून्य (0) प्रदान किया जाता है। हम भी स्टेटिक मेम्बर को क्लास का नाम एवं स्कोप रिसोल्यूशन ऑपरेटर (::) की सहायता से प्रारंभिक मान प्रदान कर सकते है।
Syntax:-
Declaration in a class:-

static data_type var_name;

Definition/Initialization outside the class:-

data_type class_name::var_name=value;

Example:-
static int objectCount;
int Test::objectCount=100;

Static Member Function:- 
A static member function is a special member function of class, which is used to access only static data members, other static member functions and any other functions. It can't able to access any other normal data member of class. Static member function is not associated with class objects.
क्लास में स्टेटिक मेम्बर फंक्शन एक विशेष प्रकार का फंक्शन होता है। जिसका प्रयोग केवल स्टेटिक डाटा मेम्बर, अन्य स्टेटिक मेम्बर फंक्शन एवं किसी अन्य फंक्शन को एक्सेस करने के लिए किया जाता है। यह क्लास के किसी सामान्य डाटा मेम्बर को एक्सेस नहीं कर सकता है। स्टेटिक मेम्बर फंक्शन क्लास के ऑब्जेक्ट्स से सम्बंधित नहीं होता है           
Syntax:-
Declaration/Definition in a class:-

static return_type func_name(arguments){
statements;
..................
}

function calling:-

class_name::function_name(arguments);

Example:-
static void showcount(){
cout << "Total objects: " <<objectCount<< endl;
}

Test::showcount();

Program:-

#include<iostream.h>
#include<conio.h>
class Test {
int a,b,c;
//static data member
static int objectCount;
public:
//static member function
static void showcount(){
cout << "Total objects: " <<objectCount<< endl;
}
// Constructor definition
Test(int m, int n, int o) {
cout <<"Constructor called." << endl;
a=m;
b=n;
c=o;
// Increase every time object is created
objectCount++;
}
};
// Initialize static member of class Box
int Test::objectCount = 0;
int main(void) {
Test::showcount();
Test  t1(2,4,7),t2(4.3, 7.0, 12.0);
clrscr();
Test::showcount();
getch();
Test t3(0,0,0);
Test::showcount();
getch();
return 0;
}

No comments:

Post a Comment