OOP Basics
Static Members
Class-Level Data & Functions
💡 Static member ek shared notice board jaisa hai — har object ki apni copy nahi hoti, sab objects ek hi shared cheez dekhte hain. Jaise ek school ka "total students" count — har student ka apna alag count nahi, sab ek hi shared number share karte hain.
static member variable class ke saare objects ke beech SHARE hoti hai — sirf ek copy poore program mein, chahe kitne bhi objects banao. Normal member variables ki har object ki apni alag copy hoti hai, static ki nahi.
static member function bhi class-level hoti hai — kisi specific object ke bina call ki ja sakti hai (ClassName::function()), aur sirf static members access kar sakti hai (kyunki uske paas "this" nahi hota — kaunsa object, ye pata hi nahi).
class Student {
public:
static int totalStudents; // sab objects share karte hain
Student() {
totalStudents++; // har naya object count badhata hai
}
};
int Student::totalStudents = 0; // static member ko file scope mein define karna zaroori
int main() {
Student s1, s2, s3;
cout << Student::totalStudents << endl; // 3 — class naam se access
return 0;
}🔗
Static member ek shared notice board jaisa hai — har object ki apni copy nahi hoti, sab objects ek hi shared cheez dekhte hain. Jaise ek school ka "total students" count — har student ka apna alag count nahi, sab ek hi shared number share karte hain.
1 / 2
⚡ Quick Recap
- static variable = poore class ke liye ek hi shared copy
- static function = object ke bina call ho sakta hai (ClassName::func())
- Static members ko class ke bahar define karna zaroori hai
On this page (1 subtopics)
Static member function ke paas "this" pointer NAHI hota — isliye wo sirf static members access kar sakta hai, non-static members ya this ko access nahi kar sakta (kyunki uska koi specific object hi nahi hai).
class Counter {
static int count;
int id; // non-static
public:
static void incrementCount() {
count++;
// id++; // ERROR: static function 'id' access nahi kar sakta
}
};
int Counter::count = 0;Tip: Utility functions jo class ke kisi specific object se related nahi hain (jaise math helpers) static banana natural hai — obj.func() ki jagah ClassName::func() se call ho sakte hain.