Static Class Members

Introduction

Object Oriented Programming में सामान्यतः class के data members हर object के लिए अलग-अलग copy में बनाए जाते हैं। लेकिन कुछ स्थितियों में हमें ऐसा data चाहिए होता है जो सभी objects के लिए समान हो और जिसकी केवल एक ही copy पूरे program में मौजूद रहे।

इसी आवश्यकता को पूरा करने के लिए C++ में static class members का उपयोग किया जाता है। Static members class से जुड़े होते हैं, न कि individual objects से, इसलिए इन्हें सभी objects के बीच share किया जाता है।

Definition

Static Class Members वे data members या member functions होते हैं जो static keyword के साथ declare किए जाते हैं और जिनकी केवल एक ही copy पूरे program में होती है, जिसे सभी objects share करते हैं।

Static Data Member का Syntax

class ClassName {
public:
static dataType variableName;
};

Static Data Member की Initialization

Static data member को class के बाहर initialize किया जाता है:

dataType ClassName::variableName = value;

Example (Static Data Member)

#include <iostream>
using namespace std;

class Demo {
public:
static int count;

Demo() {
count++;
}
};
int Demo::count = 0;
int main() {
Demo d1, d2, d3;

cout << "Count: " << Demo::count;

return 0;
}

Output:

Count: 3

Working को समझना

  • count static है, इसलिए इसकी केवल एक copy है
  • हर बार object बनते ही constructor count को बढ़ाता है
  • सभी objects उसी एक variable को share करते हैं

Static Member Function

Static functions भी बनाए जा सकते हैं जो केवल static members को access कर सकते हैं।

Syntax

static returnType functionName();

Example (Static Member Function)

#include <iostream>
using namespace std;

class Demo {
public:
static int x;

static void show() {
cout << "Value: " << x;
}
};

int Demo::x = 100;

int main() {
Demo::show();
return 0;
}

Output:

Value: 100

Static Members के गुण

  • सभी objects के लिए common होते हैं
  • केवल एक ही memory location होती है
  • class के नाम से access किए जा सकते हैं
  • object बनाए बिना भी access संभव है

Static और Non-Static में अंतर

आधारStatic MemberNon-Static Member
Copyएकहर object के लिए अलग
AccessClass सेObject से
MemorySharedSeparate
UseCommon dataIndividual data

निष्कर्ष

Static class members का उपयोग तब किया जाता है जब हमें ऐसा data चाहिए होता है जो सभी objects के लिए समान हो। यह memory को बचाता है और program को अधिक efficient बनाता है।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top